cswork / libraryOpen practice workspace

Articles

Geo Index Interview Questions: Geohash, H3, and Boundary Neighbors

Practice geo index interview questions with Geohash and H3 boundary cases, conservative candidate covers, exact radius filters, and moving-location updates.

A nearby-driver service queries only the customer's geospatial cell. A driver standing just across the cell boundary disappears, while a more distant driver inside the same cell remains a candidate. The index is returning the requested cell; the query asked the wrong geometric question.

Geo index interview questions are clearer when you separate candidate retrieval from exact membership. Geohash and H3 help organize spatial data, but a cell identifier is not an exact radius predicate or a road-travel-time estimate.

Evidence boundary: Official H3 and PostGIS documentation supplies the indexing and predicate facts linked below. The boundary coordinates, candidate ledger, and system-design recommendations are original exercises and inference. No candidate reports or employer-specific interview frequencies are claimed. Begin with Design Food-Delivery Proximity Search for Restaurants Within 10 km and define what “within 10 km” means.

What does a spatial cell buy you?

A point-to-cell mapping groups locations into keys that can support lookup, aggregation, partitioning, or caching. Resolution trades cell size against the number of keys needed to describe a region. It does not remove the need to specify coordinate system, distance units, and query semantics.

Official representation fact: PostGIS describes Geohash as a text encoding that represents a location through nested spatial boxes, with precision controlling the result. See ST_GeoHash.

Official system fact: H3 is a hierarchical global grid with hexagonal cells and unavoidable pentagons; its documentation explains the icosahedral construction and resolution hierarchy. See the H3 overview.

Engineering inference: Geohash prefixes can make regional bucketing convenient. H3's grid operations can make neighborhood traversal and aggregation convenient. Choose from the actual query, data distribution, and operational requirements instead of claiming that one geometry always wins.

Neither identifier is a globally ordered list of physical distance. Nearby points can cross a prefix boundary. Locations in the same cell can lie at opposite sides of it. String similarity and geographic proximity are related through the partitioning, not interchangeable.

Can you show the boundary failure with two points?

Original planar exercise: Use two adjacent square cells solely to make the geometry easy to calculate. The left cell covers x from zero up to one; the right cell covers x from one up to two. Both span y from zero up to one. Units are kilometers in this illustrative local plane, not latitude degrees.

The query is Q at (0.99, 0.5). Candidate A is (1.01, 0.5), and candidate B is (0.1, 0.5). The search radius is 0.05 km.

PointCellDistance from QExact radius membership
ARight0.02 kmInside
BLeft0.89 kmOutside

A same-cell lookup retrieves B and misses A. Exact filtering can reject B, but it cannot recover A if A never entered the candidate set. That is why candidate retrieval must be conservative: every true match needs a route into the candidates.

This fixture uses generic square cells. It is not an asserted H3 cell layout or a measured Geohash example. The boundary reasoning applies to spatial partitions without pretending that their actual geometry is identical.

Adding neighboring cells fixes this small fixture, but “always search eight neighbors” is not a general radius-search guarantee. The radius can span more cells, cell dimensions depend on resolution and geometry, and edge cases can change traversal behavior.

What makes a cell cover conservative?

Original correctness contract: The candidate region must cover the complete requested search region under the selected coordinate and distance model. False-positive candidates cost filtering work; false-negative candidates violate the query contract.

A radius circle generally intersects cells whose centers lie outside it. Selecting only cells with centers inside the region can miss points in the intersecting boundary portions. State whether the coverage operation includes centers, fully contained cells, or overlapping cells.

Official API fact: H3's ordinary polygonToCells uses cell centroids to determine containment. The documented experimental variant provides several containment modes, including overlapping and bounding-box overlap. See H3 region functions.

Engineering inference: Do not treat a centroid-based polygon fill as automatically conservative for retrieving every point in that polygon. Use a justified overlap cover or another conservatively enlarged retrieval region, then apply the exact predicate. Verify the library version and available binding before relying on an experimental mode.

Approximating a geodesic circle with a polygon adds another coverage question. A polygon whose edges cut inside the desired circle can lose matches even if its cell cover is correct for that polygon. Document approximation error and choose a conservative construction when completeness is required.

For an interview, draw the geometric set you need, the cells you retrieve, and the predicate applied afterward. That drawing exposes assumptions more reliably than listing an index name.

Is H3 grid distance a distance in kilometers?

Official API fact: H3 gridDistance measures the minimum number of adjacent-cell hops. It can fail for different resolutions, distant cells, or pentagonal distortion. gridDisk returns cells within a specified number of grid steps, and its output order is not guaranteed. See H3 traversal.

Grid steps are topological distance, not meters. Multiplying k by an average edge length does not automatically produce a guaranteed geographic radius cover. Cell geometry varies, and the query can lie near an origin cell's edge rather than its center.

Engineering inference: Use a grid neighborhood as a candidate-generation mechanism whose geographic coverage is justified for the chosen resolution and locations. For a correctness-critical service, test that justification near boundaries and difficult global geometry, rather than tuning k on one city-center example.

Do not interpret traversal output order as nearest-first ranking. Fetch candidate coordinates and rank by the actual distance or business score. An API returning an unordered collection is not a nearest-neighbor search result.

If traversal fails, define a fallback that preserves the service's intended behavior. An empty result caused by an API error must not be confused with a successful query finding no drivers.

What should the exact distance filter use?

Official predicate fact: PostGIS ST_DWithin uses the spatial reference system's units for geometry, while its geography form uses meters and defaults to spheroidal distance. It includes an index-assisted bounding-box comparison. See ST_DWithin.

Original query contract: Choose whether the service needs straight-line geographic distance, distance on a projected local plane, or road distance. A driver's proximity in meters does not establish travel time through a road network.

Latitude and longitude are angular coordinates. Treating raw degrees as kilometers mixes units and ignores the changing physical scale of longitude with latitude. Check coordinate order as well: swapping latitude and longitude can produce valid-looking numbers in the wrong place.

A spatial database can already provide an indexed exact-distance workflow. Do not add a custom Geohash or H3 layer merely because the question mentions an index. Explain what that layer adds, such as distributed bucketing or analytics aggregation, and what correctness responsibility it introduces.

At the antimeridian, a small geographic region may cross the longitude wrap. A naive numeric interval from the minimum longitude to the maximum can cover almost the whole globe or exclude the desired region. Keep wrap and polar cases in the geometry contract.

How do resolution and data density affect cost?

Original candidate ledger: Suppose a query retrieves 12 cells containing 8,000 records, exact distance retains 300, and business eligibility retains 40. These invented counts describe stages, not a benchmark or a guarantee for a particular resolution.

StageCorrectness requirementCost or evidence to inspect
Cell coverInclude every possible spatial matchNumber of cells and coverage boundary
Candidate fetchRetrieve the covered records consistentlyHot cells, bytes read, duplicate IDs
Exact predicateApply the requested distance modelCoordinates, units, filtering work
EligibilityApply availability and policyData age and race conditions
RankingReturn the requested orderActual distance or business score

Coarser cells can require fewer cell keys but retrieve many irrelevant points. Finer cells reduce per-cell area while increasing cover size and fan-out. Dense downtown data and sparse rural data can have different bottlenecks at the same resolution.

Measure candidate amplification: candidates fetched relative to actual matches. Also inspect per-cell skew and tail latency. An average candidate count can hide a hot cell that dominates the service's slowest requests.

Deduplicate records when overlapping covers, multiple resolutions, or migration states can return the same entity more than once. Duplicates can distort ranking, pagination, and aggregation even when distance filtering is correct.

What changes when locations move?

Engineering inference: Updating a driver's coordinates and its cell membership separately can expose inconsistent state. A query might retrieve the old cell but read new coordinates, or omit the driver during a remove-then-add transition. Define the consistency contract rather than assuming an index update is instantaneous everywhere.

One design can retain temporary membership in both cells and deduplicate by entity ID while checking the latest authoritative coordinates. That favors candidate completeness at the cost of extra reads. Another design can use atomic updates within a suitable storage boundary. The appropriate choice depends on the actual system.

Attach observation time and version to locations. A stale point inside the radius is not necessarily an available driver now. State how late, reordered, and repeated updates are processed and what age limit the product permits.

A distributed top-k query also needs a completeness argument. Fetching a fixed number of records from each cell without the requested ranking can discard closer candidates before global ranking. Explain the local retrieval order and stopping rule.

This article's index question differs from geofencing event detection. A radius lookup asks which records currently satisfy a spatial predicate; geofencing additionally reasons about noisy entry and exit over time. The two can share candidate lookup while requiring different output semantics.

Which tests reveal coverage omissions?

Original test plan: Place pairs just across each cell edge and corner, vary query radius across several cell widths, and compare indexed results with a trusted exhaustive distance calculation on a small dataset. A successful same-cell test does not validate boundary coverage.

Test empty results, dense cells, duplicate IDs, exact-boundary distances, antimeridian crossings, and the library's documented pentagon behavior. Include moving records and delayed updates when the service supports them.

Separate coverage tests from performance measurements. A faster query that omits valid records has not solved the same task. Save the failing coordinates, index resolution, cover cells, and predicate settings so an omission is reproducible.

The local checks for this article verify the two-point planar counterexample and a conservative multi-cell retrieval fixture. They do not claim full H3 integration, global geographic coverage, or a production throughput benchmark.

Five questions for geospatial design practice

These direct practice pages cover proximity search, moving entities, and alternative spatial structures. They are not candidate reports establishing current company interview frequency.

QuestionIndex follow-up
Design Food-Delivery Proximity Search for Restaurants Within 10 kmJustify a radius cover and exact filter.
Design a Real-Time Nearby-Driver ServiceHandle movement, staleness and membership changes.
Design a Geolocation Search ServiceDefine coordinate, ranking and coverage contracts.
Quadtree for 2D Geospatial PointsCompare an alternative spatial partition.
Design Radius-Based Notifications from Mobile LocationsSeparate radius matches from notification state.

Continue with Design a Real-Time Nearby-Driver Service. Explain candidate completeness, exact distance, and location freshness before discussing sharding or caching.

Sources and further reading