The interview problem

Practice prompt

Design a service that returns the nearest 20 available mobile maintenance technicians within five kilometers. One million technicians send location updates every ten seconds. Explain spatial indexing, boundary coverage, stale updates, dense urban hotspots and why a search result does not reserve a technician.

Original system-design practice, not a reported company interview. Scale, locations and calculations are illustrative. Primary reference retrieved September 27, 2026; publication date not stated; interview date not applicable.

1. Define nearby and available

Use geodesic distance from the query point, not road travel time. The user requests at most 20 results within a five-kilometer radius, filtered by tenant, skill and current discoverability. A nearby technician across a river may take longer to arrive than a more distant one; ETA is a separate service.

Return distance from the latest accepted location, its observation timestamp and availability revision. Exclude locations older than 30 seconds under the illustrative freshness policy. This is not a guarantee of the person's physical position now. GPS uncertainty, movement and delayed delivery remain relevant.

Availability means eligible to be offered work at the time checked. Assignment requires a separate conditional reservation. The API must distinguish complete results, partial results caused by failed partitions, and a complete search that found fewer than 20 candidates.

2. Separate current state from spatial candidates

authenticated location updates → validation and ordering
                              ↓
              authoritative current technician record
                              ↓ durable change stream
           spatial cell/index projections by region
                              ↓
query → conservative cell cover → parallel candidate fetch
                              ↓
       current-state, permission and freshness filtering
                              ↓
        exact distance → deterministic top-20 ranking
                              ↓
            result + freshness/completeness metadata

Begin with an indexed spatial database where its capacity meets the workload. PostGIS provides geography distance predicates in meters and can use spatial indexes to reduce candidate work. At greater scale, partition projections geographically and retain the same candidate-then-distance contract. Do not assume a custom cell service is necessary before measuring the baseline.

The authoritative record contains technician ID, session epoch, monotonic update sequence, accepted coordinates, observation/receipt times and availability revision. Reject old sequence numbers within an epoch. Authenticate a new epoch so replaying an old device session cannot move the technician backward. Validate clock skew and plausible coordinates; a fresh receipt time does not make an old observation current.

Use a durable change stream to update spatial membership and reconcile projection drift. Cell records identify the entity and location version; the current-state lookup decides whether the candidate is usable. Keep location history only as required by the product, with restricted access and retention separate from the live index.

3. Cover boundaries before filtering by distance

For an illustrative local planar grid, enumerate every cell intersecting a conservative bounding region for the query circle. Querying only the cell containing the requester misses nearby points across an edge. Two points at x=0.99 km and x=1.01 km are only 20 meters apart but fall in adjacent one-kilometer cells.

For a five-kilometer circle, the enclosing square covers 100 km² while the circle covers 25π≈78.540 km². With uniform density and no further cell-cover expansion, about 21.46% of bounding-square candidates lie outside the circle. The square produces about 27.32% more candidates than the circle contains. These percentages use different denominators.

A point offset four kilometers east and four north is inside that square but has distance √32≈5.657 km, so the exact distance filter removes it. The prefilter must tolerate false positives while avoiding false negatives under its geometry assumptions.

Real global coordinates need a spherical or ellipsoidal cover that handles the antimeridian and poles. Longitude degrees are not a fixed distance everywhere. For PostGIS, geometry distances use the coordinate system's units; geography uses meters and defaults to spheroidal distance. Specify coordinate type, SRID and distance convention rather than silently treating latitude/longitude degrees as kilometers.

4. Handle movement without hiding index lag

Suppose technician T moves from cell A to B at version 12. A projection can add the new membership before deleting the old one to reduce transient gaps. Queries deduplicate by technician ID and validate against current state, so an old membership is not sufficient evidence of the current position.

This ordering alone does not provide complete fresh search: a B query before the new membership is installed can still miss T. Either promise bounded eventual completeness with measured projection lag, or use a stronger snapshot/index protocol that actually meets a stricter requirement. Hydrating stale candidates removes wrong results but cannot discover missing ones.

A delayed delete for version 11 must not remove a newer membership for version 12. Apply projection operations conditionally by version and epoch; handle same-cell moves as updates. Reconcile out-of-order events, retries and orphan entries. Availability changes have their own revisions and must not be accidentally overwritten by an older location update.

At an assumed maximum movement speed of 15 m/s, a 20-second-old observation could be 300 meters from the current position even before GPS error. The search radius and displayed distance refer to accepted coordinates. If the product needs a physical-distance guarantee, it needs a defensible uncertainty model and a different inclusion rule, not just a smaller cache TTL.

5. Find nearest eligible results

Filter by exact radius, skill, authorization, freshness and availability before selecting the final nearest 20. Taking 20 raw nearest records and then filtering may return three results while many eligible technicians were never examined. If a partition cannot evaluate all eligibility predicates locally, fetch more candidates until the global result is justified or report the limit.

For a consistent candidate set with disjoint partitions and identical eligibility and ranking rules, each partition's local top 20 is sufficient for the global top 20: an item below 20 eligible items in its own partition cannot enter the global top 20. Duplicate cell memberships, stale state and post-fetch filtering violate the simple assumptions; deduplicate and refill as needed.

An incremental search can order cells by a valid lower bound on distance. Stop once the best possible distance from every unvisited cell exceeds the twentieth accepted result, subject to tie handling. If fewer than 20 results exist, exhaust the covered region to claim completeness. Using cell-center distance as the lower bound is incorrect because a cell edge can be much closer. This proof also requires indexed positions and distances to refer to the same snapshot: if hydration moves a candidate outside its indexed cell, that cell geometry no longer bounds the current position. Treat the live eventually consistent path as approximate, or use an explicit movement/lag bound or consistent index snapshot before claiming exact stopping.

Concurrent updates mean independently read partitions may not represent one instant. State that the default response is assembled from bounded-age reads, or implement a consistent snapshot. Do not describe a moving, eventually indexed result as the exact global nearest set at wall-clock time.

6. Size ingestion and hotspot work

One million technicians updating every ten seconds generate 100,000 updates per second. At an illustrative 200 bytes per event, ingress payload is 20 MB/s or 1.728 TB/day in decimal units, before replication and protocol overhead. Three stored copies imply 5.184 TB/day if every event is retained; the live latest-state store is a different sizing problem.

At a local density of 100 technicians/km², the ideal five-kilometer circle contains about 7,854 technicians, while the bounding square contains 10,000. At 1,000 queries/s in that density regime, scanning all square candidates would inspect ten million entries/s before additional overhead. This motivates indexes, eligibility-aware retrieval and incremental nearest-neighbor search.

Hot areas need subpartitioning and query fan-out limits. A single downtown cell can overload one owner even if geographic storage is balanced elsewhere. Splitting a hot cell requires readers to know the active partition generation and tolerate dual ownership during migration. Cache coarse candidate sets cautiously; exact position, authorization and availability still need suitable revalidation.

7. Reserve separately and handle failure explicitly

When the user chooses T, submit a reservation with an idempotency key and expected availability revision. The assignment authority conditionally changes available to reserved and records the operation atomically. Two callers may see the same search result, but only a successful reservation grants the assignment.

If a spatial shard times out, return an explicitly incomplete response or fail according to the API contract. Do not infer that a silent partition contains no closer candidates. For stale projections, expose lag and suppress results that fail freshness checks; removing every stale candidate may legitimately yield fewer results.

Protect discoverability by customer scope and technician policy. A public endpoint that returns exact locations can expose personal movement. The product may return coarse positions or distance bands while retaining precise coordinates only for authorized dispatch. This is a design decision that belongs in the API contract.

8. Verify recall and operational behavior

Compare indexed results against brute-force distance and eligibility checks on fixed snapshots. Include cell edges, corners, antimeridian crossings, poles, equal-distance ties, empty regions and dense hotspots. For each completed response, check every returned ID is eligible and no omitted eligible point outranks its last result under the chosen snapshot semantics. If fewer than 20 are returned, verify that every eligible point in the radius is included, including the zero-result case.

Inject out-of-order updates, session restarts, add/delete reordering, failed partitions, clock skew and concurrent reservations. Measure candidate amplification, projection lag, false exclusion from staleness, latency percentiles and assignment conflicts. Keep snapshot correctness tests separate from live freshness measurements.

Follow-ups: How does road distance change the index? Can you stop after one neighboring ring? Why does current-state hydration not repair a missing candidate? When is local top-k sufficient? What happens when cell splitting overlaps with movement? How should location uncertainty affect radius inclusion?

9. Self-review rubric

  • Define distance, freshness, eligibility and completeness.
  • Cover every intersecting cell and filter exact distances.
  • Handle global coordinate units and boundaries.
  • Version movement updates and acknowledge projection gaps.
  • Justify top-k stopping after filtering and deduplication.
  • Size both ingress and dense-query work.
  • Separate discovery from conditional assignment.
  • Validate against snapshot ground truth and fault scenarios.

Sources and related practice

PostGIS: ST_DWithin, publication date not stated; retrieved September 27, 2026. Primary reference for coordinate units, geography distance and indexed candidate filtering. The distributed architecture, movement protocol and calculations are original design practice.

Continue with online shard migration and inventory reservations.

Continue your preparation

Choose a connected learning path or browse more System design questions. Read our editorial method and attribution policy.