AI System DesignRecommendation and Ranking SystemsGeospatial and Contextual Local Discovery

How to Design Facebook’s Location-Aware Restaurant Recommendation Engine

Question 9 of 47 · Updated

On this page

I would build a context-aware, geographically constrained retrieval and ranking service that recommends relevant restaurants the user can realistically visit, using current catalog information, consented preferences and optional privacy-safe social evidence. Retrieve eligible businesses near the requested area first, rank them using the user’s immediate intent and predicted satisfaction, then diversify the list and revalidate mutable facts before returning recommendations.

Original interview question: How would you build a restaurant recommendation engine for Facebook?

This is a proposed restaurant discovery architecture for a large social platform, not a description of Facebook's or Meta's actual proprietary implementation. Workload, prices, scores and service objectives are synthetic design assumptions. The Discover Weekly lesson covered periodic music discovery over a global catalog. Restaurants instead have fixed physical locations, business hours, travel constraints, temporary closures, local cold start and immediate user intent. Those distinctions drive this system's design.

1. Define the product and the decision#

Imagine a user opens a local discovery surface and requests restaurants near a selected neighborhood. They might provide cuisine, budget, maximum distance, planned dining time or accessibility requirements. A personalized feed may also suggest places in a user-selected city without an explicit query. Both surfaces share the place catalog and ranking infrastructure, but their objectives differ: a search query emphasizes immediate intent, while a discovery feed emphasizes useful exploration.

The primary output is an ordered list of restaurant locations, with truthful information about opening status, price range when known, and why a result matches the user's request. A restaurant brand is not the retrieval entity: each physical branch has a separate location, hours, accessibility and availability record. Maintain a stable canonical place identifier to merge duplicate records without accidentally merging different branches.

Clarify the following before building the model:

  • Is the user searching for a meal now, later today, or browsing without a fixed time?
  • Do they want a radius, travel-time bound or a particular neighborhood?
  • Which filters are strict, and which are preferences?
  • Can the user opt out of personalization or use a manually entered area instead of precise location?
  • Does the platform support reservations or only discovery? A recommendation is not confirmation that a table can be booked.
  • Which social information is actually authorized to be used and disclosed?

The main goal is a useful local discovery session, not maximizing clicks regardless of visit feasibility. A restaurant that receives many clicks but is closed, inaccessible or far outside the requested area is a bad answer.

2. Requirements and objectives#

DimensionProposed design contract
Geographic eligibilityMatch the user-selected area or explicit distance constraint
Temporal relevanceEvaluate hours at requested local time, with exceptions and freshness
PersonalizationRespect user consent, filters and declared preferences
Ranking qualityRelevant, useful, diverse results; avoid popularity-only exposure
Online latencyIllustrative p95 under 200 ms for recommendation service, excluding external booking
FreshnessExplicit age/version contract for venue status and hours
ReliabilityLocal nonpersonalized fallback or clear unavailable/unknown state
PrivacyMinimize location and social graph access; honor visibility and deletion
ConsistencyAvoid duplicate place IDs and stale closed-place recommendations

The exact service latency, feature freshness and candidate limits must be benchmarked. Restaurant opening status is different from reservation capacity, kitchen availability and service mode. Do not infer one from another. If a user requests a table at a specific date and time, actual availability requires a separate authorized booking-provider query; return no fabricated times or guarantees.

3. Capacity and workload planning#

Assume a hypothetical platform has 10 million canonical venue records, 20 million restaurant recommendation requests per day and a short list of 300 candidates per request before ranking. These numbers are illustrative only.

  • Average recommendation request rate: 20,000,000 / 86,400 = about 231 requests per second.
  • An assumed fivefold peak gives about 1,157 requests per second.
  • Scoring 300 candidates per request implies approximately 6 billion candidate scores per day, or about 69,444 scores per second on average. Batched scoring and cheap first-stage filtering matter.
  • Ten million 128-dimensional float32 embeddings require 5.12 GB of raw vector payload, excluding identifiers, metadata, index structures, replicas and overhead.
  • At 1 KB of compact request-level exposure metadata, the base request log is about 20 GB per day. Actual per-result impression logging and features may increase volume significantly.

Demand will be geographically skewed and burst around local meal times. Global daily averages are not sufficient for sizing a regional service. Measure candidate density, cache hit rates, geospatial query latency, p99 ranking latency and catalog update fan-out.

Avoid global exhaustive ranking and one external hours lookup per candidate. Use local indexes, batch hydration, versioned catalog projections and selective revalidation. Keep booking-provider requests separate from generic discovery when real-time bookability is necessary.

4. High-level architecture#

Loading diagram…

The candidate retrieval layer reduces the search space; the ranker orders only candidates that can satisfy strict requirements. Any social or semantic candidates must still pass the same geographic and availability constraints. The place catalog owns facts, while ML predicts relevance. The model cannot manufacture opening hours, change a business address or establish that a table is available.

The offline pipeline learns from versioned exposure and outcome logs. Streaming catalog changes invalidate affected projections and indexes. The online service uses compatible versions and explicitly handles unknown or stale data.

5. Build a trustworthy place catalog#

Normalize business-provided and appropriately licensed data into a canonical record:

Field groupExamples
Identityplace_id, branch identity, canonical name, business verification status
GeographyCoordinates, address, region, local timezone
AttributesCuisine taxonomy, dining modes, price range and provenance
HoursWeekly schedule, date-specific exceptions, validity and updated_at
StatusActive, temporarily closed, permanently closed, unknown
Accessibility and dietaryVerified or business-reported attributes, evidence and freshness
QualityApproved aggregate ratings, review counts, fraud or spam quality indicators
ProvenanceSource, source record ID, version, confidence, last verification

Ingest business edits and authorized provider updates through a validated pipeline. Detect likely duplicate records using names, addresses and location, but require adequate evidence before merging branches. Preserve aliases and merge history. Handle deleted, moved or closed businesses with versioned tombstones so downstream retrieval indexes do not resurrect them.

Weekly schedules must be interpreted in the venue's timezone. Handle overnight hours, holidays, temporary closures, daylight-saving changes and conflicting provider records. A missing hours field is not evidence that a restaurant is open.

Keep status distinct from the hours schedule. A place can be listed as operational yet closed for the night; a temporarily closed place should not pass an open-now filter solely because its weekly timetable says open. Business reports can themselves be stale; surface a qualified status where appropriate and encourage confirmation when facts are uncertain.

For dietary or accessibility filters, distinguish an independently verified attribute from a business claim and an unknown value. A cuisine match alone cannot establish allergen safety. A serious allergy requires direct confirmation with the restaurant, and ranking must not imply safety without evidence.

6. Geospatial retrieval: local feasibility first#

Represent locations in WGS84 latitude and longitude. A naive Euclidean distance on raw degrees is inaccurate because longitude degrees cover different physical distances at different latitudes.

For small-to-medium catalogs, a spatially indexed database such as PostGIS can support a radius predicate using geography values in meters:

SQL
-- Illustrative schema contract: location geography(Point, 4326). -- :lon, :lat and :radius_m are validated bound parameters. SELECT place_id, ST_Distance( location, ST_SetSRID(ST_MakePoint(:lon, :lat), 4326)::geography ) AS distance_m FROM restaurant_places WHERE listing_status = 'ACTIVE' AND ST_DWithin( location, ST_SetSRID(ST_MakePoint(:lon, :lat), 4326)::geography, :radius_m ) ORDER BY distance_m, place_id LIMIT 300;

A GiST index on the geography column can help accelerate the spatial predicate. Check actual query plans and benchmark density. The SQL illustrates a hypothetical schema and parameter convention; it was not executed against a PostGIS database in this session. ST_MakePoint takes longitude before latitude. Validate coordinate ranges and do not interpolate raw user text into SQL.

At large scale, a hierarchical spatial index such as H3 can group venue IDs by geographic cell. Retrieve cells covering the desired search region, include relevant boundary cells, and apply an exact radius or polygon predicate to the returned candidates. A cell-neighbor ring is not exactly a metric circle: cell shape, resolution, pentagons and boundary cases matter. Use documented covering semantics and test recall against an exact spatial baseline.

For an explicitly requested maximum walking or driving time, straight-line distance is only a pruning heuristic. Use a routing engine for the shortlist and the user's chosen mode. A nearby restaurant across a river may require a long detour. Never invent route times when the routing dependency is unavailable; degrade transparently or omit unsupported matches.

For sparse locations, offer a larger search area only with a clear distinction or user approval when the original radius is strict. Do not quietly violate the request to fill a list.

7. Hybrid candidate retrieval#

A good system retrieves eligible venues from complementary sources:

Retrieval sourceRoleKey limitation
Geographic indexNearby venues and complete local coverageDoes not model taste
Category or lexical indexCuisine, named dishes, budget and explicit query termsMetadata gaps and vocabulary mismatch
Content embeddingsSemantically similar places from permitted text and attributesRequires geographic constraints and compatible index versions
Collaborative filteringPatterns in authorized saves, visits or interactionsSparse local overlap and exposure bias
Social evidenceRelevant authorized recommendations or aggregate social contextPrivacy restrictions and popularity bias
Local explorationDiscover newly listed or underexposed eligible venuesNeeds quality and satisfaction guardrails

For a city-level shortlist, generate local candidates, intersect semantic or collaborative candidates with geography and strict filters, deduplicate by canonical place ID, and preserve candidate-source indicators. Do not retrieve globally from a vector index, keep only a tiny top-K and then filter by city: the globally nearest embeddings may all be outside the region, leaving no local results. Prefer regional partitioning or supported filtered ANN search, with an exact local baseline to measure recall.

A practical design may retrieve up to 300 candidates after union and deduplication. Allocate source quotas dynamically according to query intent and local supply. For a named restaurant query, lexical and geographic relevance dominate; for open-ended discovery, personalization and exploration may contribute more. Quotas are operational knobs, not immutable model requirements.

A place already visited by the user can be relevant for restaurant discovery; unlike weekly music discovery, repeat visits are not inherently a failure. Tune novelty to user intent rather than banning familiar venues.

8. Contextual feature engineering#

Model the relevance of a restaurant to the current request rather than maintaining one permanent ranking for each person.

  • Request context: requested area, cuisine, budget, meal time, service mode, distance or travel preference, strict constraints.
  • Place context: cuisine metadata, aggregate quality, price range, hours and provenance, local status.
  • Geographic context: exact distance or verified travel-time estimate, regional density and local coverage.
  • Personalization: authorized explicit preferences, saves and prior interactions, recency and preference confidence.
  • Social context: permitted recommendations or aggregate information only when use and disclosure are authorized.
  • Data quality: freshness, missing attributes, review count and source confidence.

Time is evaluated relative to the restaurant's local timezone and the requested dining time, not necessarily the user's current time. A venue open now may close before the user plans to arrive. If arrival time is estimated, make the uncertainty explicit. A place's future schedule is not a guarantee of operation.

Construct historical features using the data available before the original impression. A later rating, a corrected opening-hours record or a future visit cannot be used as an earlier training input. Maintain model and feature version lineage, and distinguish missing values from valid zero values.

Be cautious when using reviews and engagement. A restaurant with very few reviews can have an extreme average rating by chance. A simple shrinkage estimate toward a relevant prior can reduce instability, but its prior and strength must be validated. Review quality and possible manipulation require separate integrity controls.

9. Social signals without privacy leakage#

A social platform may have useful social evidence, such as a voluntarily shared recommendation visible to the requesting user. Social data is not unrestricted training material merely because it exists on the platform.

Use a dedicated authorization boundary that determines which content is permitted for personalization and which details may be displayed. Respect user visibility settings, consent, blocks, deleted content and changes to relationships. Avoid using private check-ins, hidden friend activity or inferred sensitive associations as ordinary ranking features. Even an aggregate can reveal individual behavior in a tiny group; apply privacy review and suitable aggregation safeguards.

A simple governed social feature might summarize authorized recommendation evidence for a venue. If it is absent, use missingness and fall back to other evidence rather than attempting to reconstruct hidden behavior. If a friend's name or action is displayed as an explanation, revalidate visibility at response time.

The system should function without any social graph access. A user who opts out can still receive local recommendations from explicit request filters and public, permitted place metadata. Do not infer religion, health status, ethnicity or other sensitive attributes from restaurant preferences.

10. Train a contextual ranking model#

Start with a transparent scoring baseline over eligible candidates. For a hypothetical discovery request, a score can combine cuisine affinity, quality, geographic convenience and approved contextual evidence. Normalize feature scales and measure each component's contribution. Coefficients are illustrative until validated.

A production ranker can predict multiple outcomes, such as a relevant result save, meaningful place-detail visit, direction request, or an explicitly confirmed reservation when the integration supports it. Define each label window and its provenance. A directions click is not proof that the user visited, and a booking click is not a completed reservation.

For a ranking model, logistic regression or gradient-boosted trees provide useful baselines for tabular features. Learning-to-rank approaches such as LambdaMART can optimize ordering-oriented objectives using grouped impression lists. A two-tower model can assist candidate retrieval at larger scale; use a richer contextual ranker to incorporate time, distance and other request-specific features that cannot easily be represented in static embeddings.

A possible conceptual utility is:

rank_utility =
    w1 * predicted_relevant_engagement
  + w2 * predicted_useful_followthrough
  + w3 * preference_match
  - w4 * travel_inconvenience
  - w5 * repeated_unwanted_exposure

Use consistent scales and tune weights against measured satisfaction and business constraints. Do not treat this utility as a probability. Do not optimize click-through in isolation: an attractive image can generate clicks without a useful dining outcome.

Position bias and exposure bias are central. The old ranker determines which venues appear and where. Unshown restaurants are not negative examples. Log served impressions with position and policy version, and distinguish explicit dislikes from ignored impressions. If the platform has an approved exploration policy with known probabilities, counterfactual methods may be useful under their assumptions. Otherwise use representative audits and guarded experiments; do not claim causal gains from observational click data.

11. Availability, hard filters and diversity#

Loading diagram…

Distinguish strict constraints from soft preferences. If the user requests open-now restaurants within two kilometers, unknown opening status cannot count as a verified match. If the user is casually browsing, closed or unknown-hour places can be shown with truthful labels. A required attribute such as wheelchair access should use an appropriate verification standard and explicitly identify unknowns.

After filtering, apply diversity to reduce repeated branches, cuisines or nearly identical options where it serves the request. A cuisine cap is sensible for open-ended exploration, but not for a query that explicitly requests only one cuisine. A maximal marginal relevance approach can balance relevance and redundancy, provided similarities and utilities are on compatible scales. Avoid forcing diversity that contradicts explicit intent.

If there are fewer valid results than the requested list length, return fewer results or offer labeled alternatives. Do not relax hard constraints silently. Preserve stable, deterministic tie-breaking for reproducible pagination.

12. Practical Python implementation: geographic filtering and ranking#

The following executable standard-library example implements a small open-now discovery query using great-circle distance, a simple normalized affinity/distance score, canonical-ID deduplication and a configurable cuisine cap. It operates on fabricated records, not real restaurants, and assumes the input OPEN status is already validated for the requested time. It is not a live availability service or a trained ranker.

PYTHON
from math import radians, sin, cos, asin, sqrt, isfinite def distance_km(lat1, lon1, lat2, lon2): for lat, lon in [(lat1, lon1), (lat2, lon2)]: if not all(map(isfinite, (lat, lon))) or not -90 <= lat <= 90 or not -180 <= lon <= 180: raise ValueError('invalid coordinates') a, b = radians(lat1), radians(lat2) dlat, dlon = b-a, radians(lon2-lon1) h = sin(dlat/2)**2 + cos(a)*cos(b)*sin(dlon/2)**2 return 6371.0088 * 2 * asin(sqrt(min(1., max(0., h)))) def rank(rows, lat, lon, radius, k=3, cuisine_cap=2): distance_km(lat, lon, lat, lon) if not isfinite(radius) or radius <= 0 or type(k) is not int or k < 0 or type(cuisine_cap) is not int or cuisine_cap < 1: raise ValueError('invalid limits') candidates = [] for rid, rlat, rlon, cuisine, status, affinity in rows: if status != 'OPEN': continue if not isfinite(affinity) or not 0 <= affinity <= 1: raise ValueError('invalid affinity') d = distance_km(lat, lon, rlat, rlon) if d <= radius: score = .7 * affinity + .3 * (1-d/radius) candidates.append((-score, rid, cuisine)) selected, seen, counts = [], set(), {} for _, rid, cuisine in sorted(candidates): if len(selected) == k: break if rid in seen or counts.get(cuisine, 0) >= cuisine_cap: continue selected.append(rid) seen.add(rid) counts[cuisine] = counts.get(cuisine, 0)+1 return selected rows = [('a',0,0,'A','OPEN',.9),('b',0,.001,'A','OPEN',.8), ('c',0,.002,'B','OPEN',.7),('d',0,.001,'B','CLOSED',1.), ('e',0,.1,'C','OPEN',1.),('f',0,0,'C','UNKNOWN',1.), ('a',0,0,'A','OPEN',.9)] assert distance_km(0,0,0,0) == 0 assert 22 < distance_km(0,179.9,0,-179.9) < 23 assert rank(rows,0,0,2) == ['a','b','c'] assert rank(rows,0,0,2,cuisine_cap=1) == ['a','c'] assert rank(rows,0,0,2,k=0) == [] assert rank(rows,0,0,.05) == ['a'] assert rank([],0,0,2) == [] assert rank([('z',0,0,'A','OPEN',.5), ('a',0,0,'B','OPEN',.5)],0,0,2) == ['a','z'] for fn in [ lambda: distance_km(91,0,0,0), lambda: rank(rows,0,0,0), lambda: rank([('a',0,0,'A','OPEN',float('nan'))],0,0,2) ]: try: fn() except ValueError: pass else: raise AssertionError('invalid input accepted') print('11 checks passed')

Observed local Python output:

11 checks passed

The Haversine formula approximates spherical great-circle distance. The antimeridian test checks that two nearby longitudes on opposite sides of the date line are not treated as far apart. It is not travel distance. The ranking checks cover strict opening status, radius, deduplication, diversity, empty output, deterministic tie-breaking and invalid numeric inputs. The example uses one cuisine per record, assumes consistent duplicate metadata, and treats all non-OPEN values as ineligible. A production catalog must reconcile contradictory records before ranking and support multi-cuisine venues and actual freshness checks.

The implementation scans N supplied records and sorts at most N candidates, giving O(N log N) worst-case time and O(N) auxiliary space. A production service uses a spatial index to restrict N and can employ a bounded heap or optimized ranker where appropriate. The checks do not validate user satisfaction, travel-time accuracy, provider availability, model calibration or production scalability.

13. Real-time serving and catalog freshness#

Loading diagram…

An illustrative request contains a selected location or area ID, requested dining time, distance/travel bound, intent filters, authorization context and pagination cursor. Return place IDs, display information, relevant distance/route information where supported, status provenance, data age and a stable result cursor. Do not include hidden social information in the response.

For pagination, bind the cursor to the request context and a compatible candidate/ranking version or short-lived snapshot. Revalidate changes such as closures on later pages. Avoid offset pagination over continuously changing ranks without acknowledging duplicates or omissions.

Cache public regional candidate pools by area, time bucket and catalog version. Cache personalized responses only with an appropriate privacy-scoped key, short retention and invalidation for preference or consent changes. Do not share an exact-location personalized result between unrelated users. Avoid retaining precise coordinates in broadly accessible logs.

If the restaurant is permanently closed or its information is corrected, propagate tombstones through the geo index, vector index and caches. Reconcile derived indexes with the authoritative catalog periodically. An event-driven update accelerates freshness, but durable reconciliation catches missed events.

14. Storage and scalability#

StoreAccess pattern and role
Canonical place databaseAuthoritative place identity, status and versioned attributes
Geospatial indexRadius/polygon/cell retrieval
Lexical indexCuisine, name and structured attribute retrieval
Vector indexRegional semantic and preference retrieval
Online feature storeBatched, versioned request-compatible feature reads
Restricted social serviceAuthorized evidence only, with visibility checks
Event log and historical lakeCatalog changes, exposure and feedback lineage
Model registryCompatible retrieval, ranking, preprocessing and evaluation artifacts

Shard by region or spatial partition where appropriate. Very dense cells can produce hot partitions; choose adaptive subdivision, load balancing or separate high-volume regional workers based on measurements. Queries near geographic boundaries need coverage across partitions. Validate deduplication and exact eligibility after union.

Use parallel retrieval with a common deadline, bounded candidate counts and batched hydration. A slow optional social service should not prevent public local discovery. Route calculations may be more expensive than tabular inference; use them selectively for eligible shortlist items when actual travel time is needed.

Pin embedding and index versions during rollout. A newly trained encoder may not be compatible with old indexed vectors. Build a compatible new index, shadow query it, verify retrieval recall and switch atomically or use a documented versioned transition.

Control cost by caching shared data, coalescing catalog updates, filtering before expensive scoring and using a simple ranker where quality is adequate. Benchmark CPU versus accelerator options rather than assuming a deep model is necessary.

15. Cold start and local coverage#

New user: use a manually selected area, explicit filters, trustworthy local quality signals and diverse discovery. Offer optional preference selection; do not force location sharing. A user may travel, so recent area-specific context should override a stale home-area assumption.

New restaurant: use verified metadata, content representation and reasonable regional priors. Allow approved exploration among eligible venues so new places can obtain exposure. Avoid treating the absence of reviews as proof of poor quality.

New or sparse region: assess catalog coverage and freshness first. A recommender cannot rank places that are absent from its catalog. Use conservative local baselines, return fewer trustworthy matches and clearly offer to broaden the search. Monitor coverage rather than silently substituting a distant popular restaurant.

Popularity feedback loops can concentrate exposure among established venues. Evaluate long-tail coverage, relevance and user satisfaction together. A diverse list is not necessarily better if it ignores the requested cuisine or returns unsuitable businesses. Exploration should operate within the user's constraints and quality standards.

16. Evaluation and experiments#

Separate retrieval, ranking, factual correctness and product outcomes.

LayerMetrics
RetrievalRecall@K against judged eligible results, geographic coverage, index freshness
RankingNDCG@K, precision@K, relevance judgments, useful outcome calibration
EligibilityStrict-filter violation rate, duplicate rate, closed-place errors, unknown-status labeling
DiversityCuisine/branch coverage, redundancy, exposure distribution by relevant cohorts
User outcomeSaves, useful detail visits, directions, satisfaction, confirmed outcomes when available
Systemp95/p99 latency, timeouts, fallback rate, catalog lag, feature freshness

For example, a synthetic list of five results contains three relevant venues according to a human relevance judgment. Precision@5 is 3/5 = 0.6. If four relevant venues exist in the evaluated candidate universe and three are retrieved, recall is 3/4 = 0.75. The completeness of relevance judgments matters; real evaluations rarely observe all possible relevant restaurants. NDCG additionally weights relevant items by rank.

Evaluate using time-separated impressions and point-in-time catalog snapshots. Assess new users, new places, dense cities, sparse regions, missing hours, and explicit query intent separately. A ranking model may improve NDCG while worsening availability correctness, so require eligibility guardrails independently of model quality.

Use controlled experiments with a suitable assignment unit, predefined primary metrics, adequate duration and uncertainty intervals. User-level assignment can be appropriate for a discovery interface, but geographic/business exposure can introduce interference. Consider the actual marketplace and statistical design. Analyze intent-to-treat rather than only users who clicked a result. Monitor complaints, privacy failures, misleading status and provider load. Do not run experiments that knowingly violate hard filters or privacy restrictions.

Separate offline relevance metrics from actual dining outcomes. A person clicking directions may not visit, and absence of an observed visit may reflect missing instrumentation rather than dissatisfaction. Use explicit consent and legitimate purpose for any follow-through measurement.

17. Privacy, security and trust#

Exact location, social relationships and dining behavior can be sensitive. Use purpose-limited data, granular authorization, encryption, short retention for precise location, and pseudonymized training identifiers where appropriate. Support user-selected location, consent withdrawal and deletion propagation across feature stores, caches, indexes and future datasets. Define treatment of backups and already trained artifacts through approved governance.

Apply business-content integrity checks to avoid spam, impersonation, misleading restaurant records and manipulated reviews. Treat business-provided text and reviews as untrusted data. If an LLM is used for explanation generation, it should summarize authorized facts rather than invent opening hours, accessibility attributes, prices or endorsements; validate structured outputs and keep tool access constrained.

Keep sponsored placements clearly distinguishable from organic recommendations if applicable. Paid exposure must not override strict user filters or factual correctness. Monitor provider visibility and customer outcomes in appropriately governed cohorts; avoid unauthorized sensitive profiling. Current legal and platform obligations require expert review, not assumptions based on this hypothetical system.

18. Failure handling and operational monitoring#

FailureSafe behavior
No location permissionUse manually selected area or request an area without forcing precise access
Geo index unavailableUse a validated compatible local fallback or explain inability to locate results
Social service unavailableOmit social features and explanations
Personalization model unavailableUse eligible local relevance baseline
Stale or conflicting hoursMark unknown; exclude from strict open-now matches
Missing route serviceDo not claim travel time; offer distance-based alternatives only as appropriate
Booking-provider failureDo not claim confirmed table availability
Place deletion or closureInvalidate projections and prevent stale resurrection
No eligible candidatesReturn honest empty/short result and offer explicitly broadened options

Use deadline propagation, circuit breakers, bounded retries and isolated capacity for catalog reindexing versus live serving. Log dependency failures and fallback sources without raw sensitive coordinates. Monitor catalog freshness, index drift, duplicates, filter violations, calibration and regional quality. A rise in closed-place complaints may indicate a catalog synchronization issue rather than a ranker problem.

Model rollback must preserve current factual eligibility and consent state. Restoring an older ranking model is not permission to restore deleted records or old social permissions. Test invalidation, consent changes, boundary queries, hours exceptions and unavailable dependencies before release.

19. Interview-ready answer#

I would begin by clarifying the requested location, meal time, strict filters and whether the feature provides discovery or actual reservation availability. I would build a canonical place catalog with verified geography, versioned opening hours and business status. A spatial index retrieves nearby candidates, enriched by lexical, content and collaborative retrieval; every source must obey the same geographic and availability constraints.

I would assemble point-in-time context features, use consented preferences and only authorized social evidence, then rank eligible places with a lightweight learning-to-rank or tabular model. A final reranker would enforce deduplication, appropriate diversity and fresh catalog validation. New users receive a useful local baseline, while new venues receive content-based recommendations and governed exploration.

For scale I would use regional indexes, batched feature reads, shared candidate caches and event-driven catalog updates. I would evaluate retrieval recall, ranking relevance, factual eligibility, privacy, local coverage and useful user outcomes, and provide safe fallbacks when ranking or availability data is unavailable. Unlike a weekly music playlist, the crucial constraint is that a restaurant recommendation must remain geographically and temporally useful at the moment the user needs it.

References and research transparency#

The authorized offline research exception was applied. These established primary research and official technical references support geospatial retrieval, recommendation modeling, ranking, evaluation, privacy and streaming. Their current availability and contents could not be live-verified, and the current Supabase changelog was unavailable. The three diagrams use standard triple-backtick Mermaid fences and were reviewed structurally; the Mermaid parser is not installed in the local runtime, and frontend rendering was not tested. The standard-library Python example was executed locally with all eleven checks passing; the illustrative PostGIS SQL was not executed. The proposed architecture and numerical examples do not establish Facebook's current implementation or empirical results.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningMLOpsPython