Skip to main content

Discovery Platform Low-Level Design

This document is the implementation companion to Discovery platform architecture. Compass owns policy and request construction. TypeSense executes primary retrieval and ranking.

Runtime Contract

Compass never reimplements primary search ranking in application code. It may apply a narrow final rerank only for data TypeSense cannot safely know at query time, such as pincode delivery or future seller-offer selection.

Discovery Product Document

Index one canonical product family, not one document per SKU/size variant.
Index title, brand, category, concern, ingredient, product type, format, controlled description, facets, numeric values, and ranking fields. Leave display-only data unindexed. Price, stock, listability, and Rx state are separate fields.

Query Understanding

Pipeline

Use deterministic controlled dictionaries and parsers first. Do not begin with an LLM classifier.
Protected brands, product families, and molecules are recognized before typo/rewrite behavior and must never be rewritten into generic words.

Intent signals

Ambiguous queries may retain multiple candidates. Log confidence and evidence in the Compass explain record.

Numeric extraction

Use typed parser rules, not text search, for explicit values. Only high-confidence explicit values become hard filters. Ambiguous values, such as light sunscreen, become controlled ranking preferences or later hybrid-search signals.

Query-plan type

For spf above 50 sunscreen for oily skin under 700, Compass creates:

TypeSense Request Compilation and Ranking

Compass loads the ranking profile and matching active rules, then compiles TypeSense parameters. TypeSense performs the actual relevance score, filtering, grouping, sorting, curation, and pagination.

Ranking precedence

Compass profiles are governed configuration. TypeSense executes them. A profile defines searchable fields/weights, allowed sorts, out-of-stock policy, ranking signals, and lexical/hybrid mode. Use native TypeSense controls first:

Eligibility and Final Validation

Push broad filters into TypeSense, then revalidate in Compass.
No pin, override, experiment, campaign, or TypeSense parameter can resurrect an ineligible item.

Core Surface Designs

The following sections are the implementation contracts for the four core discovery surfaces. They use one canonical product collection and one shared eligibility/ranking policy; they do not create separate product indexes per page type.

Search API contract

Compass validates page bounds, allowed filter fields/values, sort, platform, session identity, and request size before query understanding begins. The client never sends TypeSense query parameters directly.

Search execution sequence

search_id identifies the exact returned list. The explain record stores the raw query, normalized query, QueryPlan, TypeSense request, active rule/profile/configuration versions, candidate exclusions, result positions, fallback step, provider, and latency.

Search profiles

Profiles are stored in Compass and compiled to TypeSense request parameters. They are not code branches.
Examples of profile selection:

Filters, sorting, grouping, and pagination

Compass always adds mandatory filters, then adds explicit user filters and high-confidence extracted filters.
Product-family grouping is mandatory for search and browse. The product document is the canonical family; displayVariants provides the price/variant shown on the card. Pagination always occurs after TypeSense grouping. A filter or sort change resets to page one server-side. Sort semantics:

Search fallback ladder

Fallback is explicit and measured. It is not a hidden retry loop.
Medical/Rx and deliberately out-of-scope terms bypass generic semantic alternatives and follow consultation/clinical or honest out-of-scope policy. Each response carries fallback.step; PostHog records it. TypeSense nohits_queries tracks raw engine no-hit demand, which is distinct from a fallback-rescued user result.

Search failure behavior

Search measurement

Required PostHog properties for search_executed include search_id, raw/normalized query under access policy, intent, extracted entities/filters, profile/version, configuration version, provider, results and positions, result count, fallback, latency, platform, and surface. Track zero result, fallback rescue, reformulation, search-to-PDP, search-to-cart, search-to-order, latency, rule exposure, and index freshness. Compare these against Netcore during migration.

Autosuggest

Design principle

Autosuggest is a grouped router, not a smaller flat search-results page. TypeSense identifies matching candidates and maintains native popular-query data. Compass determines group, destination, privacy/safety, curation, and final suggestion quality.

Collections

Use one main product collection and small entity collections. Do not create a separate product collection for every suggestion type.
analytics_popular_queries_v1 is a normal TypeSense destination collection populated by its popular_queries native analytics rule. It is the popular-query source; no separate leaderboard service is required.

Suggest API contract

The client debounces 150-250ms, cancels an older request when a newer prefix exists, and does not call suggest for a stale input value. Compass uses a stricter latency budget than full search.

Suggest execution sequence

Group order is deterministic:
An exact Acne UV product family must outrank a broad Acne concern. A popular query never bypasses safety or quality gates.

Suggest response contract

Before a TypeSense popular query is displayed, Compass checks:
  • It is not a prescription, medical, sensitive, abusive, or blocked phrase.
  • It has an acceptable recent successful-result rate and availability profile.
  • It is not a near duplicate of an existing entity/product suggestion.
  • It is not expired/blocked by a merchandising or compliance rule.
  • It has enough recent traffic according to the configured threshold.
TypeSense handles popularity aggregation and prefix matching; Compass decides whether a popular query is eligible to surface.

Empty-prefix suggestions

For an empty prefix, do not run normal entity multi-search. Return, in policy order:
Prescription and sensitive health searches never reappear in a shared/recent surface without explicit privacy approval.

Suggest analytics

The client sends visible suggestion impressions only after the dropdown is visible. Suggestion clicks include suggestion_id, group/type, rank, source, prefix, destination, session, and resulting search/page context. suggestion_shown and suggestion_clicked go to PostHog; native TypeSense analytics continues to aggregate actual search submissions rather than every keystroke.

Browse and PLP

Page definition

Browse pages are query templates over discovery_products_v1, not separate product indices.
Examples:

Browse request flow

Filter configuration

Filter semantics are fixed:
Compass rejects unsupported filters rather than allowing arbitrary filter_by expressions from clients. Empty-filter states return clear removal/relaxation choices; they never silently change user filters.

Browse merchandising and content

Page-level rules use the same control plane as search:
  • Pins/hides compile to TypeSense overrides or request-time controls.
  • Simple boosts/buries compile to profile/evaluation parameters.
  • Content slots are resolved by Tetris/CMS after product retrieval.
  • Card badges derive from controlled product flags and Compass rules; badge priority/max count is configuration.
Do not put banners or CMS content in TypeSense documents. TypeSense returns product data; Tetris owns content composition.

Browse SEO and events

Stable page IDs and canonical URLs are independent of display names. Renames preserve redirects. Filtered URLs receive explicit index/noindex policy. PostHog plp_viewed records page ID/type, products/positions, profile/config version, active filters, sort, and content-slot IDs. Client events record visible cards, filter/sort changes, content interactions, and PDP clicks.

Recommendations

Design boundary

Recommendations use a pipeline, not generic “similar products” search. TypeSense can retrieve attribute-compatible candidates, but Compass applies the strategy, routine logic, safety, exclusions, overrides, fallback, and measurement.

Widget request contract

Strategy configuration

Candidate source order should begin with deterministic sources:
An LLM is never the primary product recommender.

TypeSense recommendation retrieval

For attribute-based similarity, Compass builds a constrained TypeSense query from the anchor product:
For best_used_with, the query must prefer a complementary routine step and exclude duplicate actives. For similar, it can retain the same product type/concern. The strategy decides this; a generic vector-nearest-neighbor query is insufficient.

Routine and safety policy

Compass stores controlled relationship tables:
Before a widget can render, Compass excludes:
  • Anchor product itself.
  • Rx products from all promotional widgets.
  • Out-of-stock or unlistable products.
  • Forbidden category/widget combinations.
  • Same routine step where complementarity is required.
  • Duplicate active ingredients where redundancy is forbidden.
  • Known ingredient conflicts and declared safety cautions.
A shorter widget is preferable to weak padding. Every selected item records which source/fallback supplied it.

Recommendation merchandising, fallback, and events

Merchandisers can pin, hide, cap, floor, or fully replace a widget with a curated list through the same Compass rule model. Widget rules are scoped by widget type, surface, anchor product/family/category, and schedule.
Compass/Tetris emits widget payload context: widget ID, strategy/version, anchor, slots, selected products, source/fallback, profile/configuration version. The client sends a visible widget impression only when rendered in viewport, then click/add-to-cart context. PostHog measures impression-to-click, click-to-cart, attributed revenue, fallback serve rate, empty rate, and session-level effect.

End-to-End Use Cases

Exact product

Vector search is disabled or strongly downweighted.

Brand

Category, ingredient, concern

Hinglish

Hinglish aliases are Compass-controlled rows with locale, canonical entity, source, confidence, version, and approval state. They are not solely vector-model guesses.

Autosuggest

Browse/PLP

Use hybrid retrieval only after lexical, Hinglish, fixtures, and baseline metrics are proven. Exact product/brand/ingredient and approved alias queries remain lexical dominant. Medical/Rx queries do not become semantic merchandising.

Redirect, medical, and fallback

Every redirect, fallback, and consultation decision is recorded in Compass explain evidence and PostHog.

Recommendations

Merchandising Compilation

Compass PostgreSQL is the rule source of truth. TypeSense is an execution target.
Core records:
typesense_rule_sync records TypeSense resource type/ID, source rule version, pending|synced|failed status, time, and error. Disabling a rule immediately removes it from Compass active configuration and queues TypeSense deletion. For a pin:

Event Contract and Routing

Portable event envelope:
Compass returns an opaque signed discovery_context_token per result. Clients pass it unchanged to clicks and add-to-cart; Vector/Medusa validates it and persists primary discovery attribution on the cart line. The order event uses that persisted line attribution.

Provider Migration Runtime

Assignment is server-side and sticky:
Shadow returns Netcore, calls TypeSense asynchronously, disables TypeSense analytics, and records normalized comparison data. Public TypeSense traffic falls back to Netcore on invalid response, timeout, index freshness breach, or safety failure.

Tests and Operational Evidence

Golden cases include exact products/brands, typos, protected terms, Hinglish aliases, structured filters, redirects, zero-result recovery, Rx handling, pins/hides, and recommendation exclusions. For every search, retain a short-lived explain record with raw/normalized query, query plan, TypeSense parameters, filters, active profile/configuration version, applied rules, excluded candidates/reasons, score contributions where available, result positions, fallback, provider, and latency.