Nearby Venue Feed: Real-Time Top-K Ranking as You Explore a Map
Machine LearningModel answerLast updated
Design a low-latency system that surfaces the most relevant K venues within a moving map viewport, covering spatial indexing, candidate retrieval, personalized re-ranking, and caching.
Nearby Venue Feed: Real-Time Top-K Ranking as You Explore a Map
You're building the backend for a consumer map app. As a user pans and zooms, the map continuously shows pins for the most relevant venues (restaurants, attractions, shops, etc.) inside their current view. The experience needs to feel instantaneous and personal.
Design the end-to-end system. Your answer should cover:
- Requirements and scale — functional behavior, latency targets (aim for p95 ≤ 150 ms end-to-end), availability, and rough throughput numbers
- API contract — what the client calls, what it gets back, and why the response shape supports caching
- Spatial indexing strategy — how you partition and index hundreds of millions of venues globally; compare the main options and justify your choice
- Candidate generation — how you efficiently find ~1–2k candidates for a given viewport without scanning all venues
- Retrieval vs. re-ranking — when you'd use approximate nearest neighbor (ANN) search versus a learned ranking model, and how you combine them; discuss decision criteria like latency budget, personalization depth, data sparsity, and recall requirements
- Caching layers — client, edge/CDN, and backend; what you can cache, what you can't, and how you maintain freshness without stale results
- Incremental updates — how edits to venues and trending signals propagate without invalidating everything
- Operational concerns — deduplication across tile boundaries, smooth pagination while panning, load shedding under traffic spikes, cold-start for new users and new venues, offline and online evaluation, and cost
A strong answer reasons about trade-offs explicitly, gives concrete numbers where useful, and explains what breaks if you make the wrong architectural choice.
Hints
Hint 1
Start by converting the viewport into discrete map tiles rather than a raw bounding box. Tile-keyed responses are cacheable; bbox-keyed ones are not — think about why that matters before designing the cache layer.
Hint 2
Separate candidate generation from ranking. The spatial index job is to narrow hundreds of millions of venues down to a few thousand cheaply; the ranker's job is to order those few thousand by relevance. ANN and learned ranking solve different problems and work best in combination, not in competition.
Hint 3
Freshness and caching are in tension. Ask yourself which part of the result changes fast (personalized scores, trending signals) versus slowly (which venues exist in a tile). That split tells you exactly what to cache at the edge versus recompute per-request.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Requirements and Scale
Functional requirements
- Return the top-K venues (K ≈ 20–50 visible pins) for a user's current viewport, personalized by their history, category affinities, and social graph.
- Results update as the user pans and zooms; pins should not visually overlap.
- Venue data must reflect recent changes: new listings, updated hours, real-time popularity.
Non-functional targets — state numbers explicitly
- ~200M venues globally, ~100M DAU, peak viewport-change events around 300k/s. After client-side debouncing and cache hits, backend load is roughly 50k QPS.
- p95 end-to-end latency: 150 ms. A realistic budget:
| Stage | Budget |
|---|---|
| Client debounce + render | ~30 ms |
| Network to edge | ~30 ms |
| Candidate generation | ~15 ms |
| Feature fetch | ~15 ms |
| Ranking model | ~25 ms |
| Merge + slack | ~35 ms |
- Availability: 99.9%. Degrade gracefully to non-personalized results; never return an empty map.
2. API Design
GET /v1/venues?tiles=z/x/y,...&user_token=...&k=30&cursor=...
→ {
tiles: [{
tile_id: "z/x/y",
version: "abc123",
venues: [{ venue_id, lat, lng, score, category }],
next_cursor
}]
}
Key decision: tile-keyed, not bbox-keyed. A floating-point bounding box produces near-zero cache hit rates because every pan yields a unique coordinate string. Tile IDs are discrete, so edge caches work. The client requests only newly exposed tiles on each pan, reusing cached data for tiles already in view.
3. Spatial Indexing
S2 or H3 cells for the backend index. Both offer hierarchical IDs and near-uniform cell areas. Geohash is simpler but has rectangular distortion at high latitudes and neighbor-discontinuity issues at cell edges that make range queries unreliable near boundaries. Either way, viewport coverage is always computed as a cell union — never a single prefix query, which would miss venues near cell edges.
Per-zoom precomputed tile lists. Each tile at zoom level z stores the top-N venues (N ≈ 200) by a static quality prior, merged from its child tiles. Zoomed out, only prominent venues appear. You never scan millions of rows at query time.
Adaptive splitting for density. Dense areas like city centers get further subdivision so each leaf cell holds a bounded count. Sparse areas stay at a coarser level.
R-trees for polygon venues (parks, campuses, large malls). Index by bounding box; assign each to a single owning tile by centroid to avoid duplicating them across tile boundaries.
4. Candidate Generation
- Cover the viewport with ~4–16 cells at the appropriate zoom level. Pad by one cell ring to prefetch for anticipated panning.
- Geo source: union the precomputed per-tile top-N lists. Most of this comes from edge cache.
- Personal source: run ANN over venue embeddings using the user's embedding vector, constrained to the covering cells.
- Social/trending source: venues recently visited by friends, and spots with elevated activity in the last 5–60 minutes.
- Clean up: merge, deduplicate by
venue_id, apply an exact bbox filter, drop closed or unavailable venues. Cap at ~1–2k candidates.
5. ANN vs. Learned Ranking
These are complementary, not interchangeable. ANN improves recall by surfacing semantically relevant venues the geo list might miss. The learned ranker determines ordering given the full feature set.
| Criterion | Lean on ANN | Lean on exhaustive geo + ranker |
|---|---|---|
| Candidate count | Large (>5k: dense area, zoomed out) | Small (<2k): score all, full recall |
| Relevance signal | Semantic / personal | Mostly prominence + distance |
| Personalization depth | Heavy user with signal | New or anonymous user |
| Embedding quality | Dense data, reliable embeddings | Sparse POIs, noisy embeddings |
Combining them correctly: Partition the ANN index by S2 cell at a coarse level (~level 10). Use filtered HNSW with a cell-ID attribute, or query only partitions intersecting the viewport. Pre-filter geographically, then run ANN — post-filtering a global ANN wastes recall on out-of-view results and is hard to reason about.
Take the top-M (~300) from ANN, union with geo and social sources, then pass the merged set to the ranker.
Ranker features: distance to viewport center, zoom level, open-now status, user–category affinity, friend-visit count, trend velocity, quality prior, ANN similarity score.
Post-ranking: apply spatial diversification — a greedy pass enforcing minimum pixel distance between pins, plus per-sub-cell caps. Without this, the top-K cluster in one block and pins overlap. Add sponsored slots and safety filters last.
6. Caching
- Client: cache tile responses by
tile_id + versionusing ETags. Panning reuses already-loaded tiles. A zoom change maps to parent or child tiles, both of which likely exist in cache. - Edge/CDN: cache the non-personalized candidate list keyed by
z/x/y/version, TTL 1–5 minutes. Hit rates of 80–90% are achievable because popular areas dominate traffic. Personalization is applied server-side as a small delta — either by re-ranking the cached candidates with live user features, or by shipping a compact user vector to the client for lightweight local re-ranking. - Backend: in-memory LRU for hot tile lists and user feature vectors.
Never cache by raw bounding box.
7. Freshness and Incremental Updates
- Venue edits: change-data-capture (CDC) flows to a message queue, then to the index updater. The updater increments the affected tile's version, which naturally invalidates edge cache entries. Target propagation under 1 minute.
- Trending signals: a streaming feature store (e.g., Flink) with 1–5 minute windows, read at ranking time. Cached candidate lists stay valid; scores stay fresh.
- Embeddings and tile priors: rebuild nightly; run a delta job for new venues hourly. This keeps costs bounded.
8. Panning, Dedup, Load Shedding, Cold Start
Panning pagination: requests are per-tile and stateless. The client tracks which tiles it has and fetches only newly revealed ones. "Load more" within a tile uses a per-tile cursor. Apply hysteresis — don't re-request tiles the moment they re-enter the viewport from a small pan; buffer by a few hundred pixels.
Deduplication: venues near tile boundaries may appear in multiple tiles' candidate lists. The client deduplicates by venue_id after merging tile responses.
Load shedding: under spike conditions, skip personalization and return the precomputed non-personalized tile list with a flag so the client knows. This makes the latency SLO a soft boundary rather than a hard one that causes timeouts. Never shed to empty results.
Cold start:
- New user → fall back to global popularity + distance, no ANN.
- New venue → assign a quality prior from category and location; it enters ANN once embeddings are computed (within hours).
9. Evaluation and Common Mistakes
Offline: precision and recall at K against held-out engagement logs; embedding retrieval recall vs. exhaustive ground truth.
Online: A/B test on click-through rate, dwell time, and pin interaction rate. Watch for position bias in your training data.
Common mistakes to avoid:
- Caching by raw bounding box — kills hit rate.
- Running ANN globally and post-filtering geographically — wastes recall and makes latency unpredictable.
- Skipping spatial diversification — top-K venues cluster spatially and pins overlap.
- Conflating candidate generation recall with ranking quality — optimize them separately with different metrics.
- Rebuilding the entire tile index on every venue edit — use versioned incremental updates instead.