Architecture: Scalable Search Product
This is the architecture behind the decision recorded in ADR-00007, satisfying the requirements in BRD-006 and SR-006. Architecture-00005 already documents the genuine Strategy pattern behind searchProducts (domain.SectionSearchStrategy, the six-strategy registry, GlobalSearchStrategy dialing search-service over gRPC) — this doc does not repeat that. It instead covers what happens on either side of that dispatch: the Atlas Search query mechanics inside search-service, the REST suggest/typeahead path that bypasses GraphQL entirely, the independently-owned filter-schema endpoint, and the specific Flutter screens (dashboard/search/, dashboard/filter/, dashboard/shop/shop_view.dart) that call all three.
Diagram

The diagram shows search-service’s Atlas Search index sitting on top of the same product_search collection search-service denormalizes into via Pub/Sub (see search-service) — there is no separate search cluster and no second synchronization pipeline, which is the load-bearing fact behind ADR-00007’s decision. As in Architecture-00005, treat any bidirectional arrow between shop-service and search-service as a drawing simplification — the real call direction is one-directional, shop-service → search-service only (SR-005 NFR-05).
Components
| Component | Language / Runtime | Role |
|---|---|---|
search-service |
Go | Owns the product_search MongoDB collection and its Atlas Search index (product_search_index), kept in sync via four independent Pub/Sub subscriptions (see below). Serves ProductSearchService/SearchProducts (gRPC, ID + count only) to shop-service, and GET /client/api/v1/product/full-search (REST, SuggestProducts) directly to ui-application. |
shop-service |
Go (gqlgen) | Default searchProducts path (GlobalSearchStrategy) calls search-service for matched IDs, then hydrates those IDs via product-catalog’s GetProductDetailsByIDs and inventory-service’s GetProductPricing (gRPC). Independently owns GET /api/v1/filter/schema, sourced from its own category_mapping collection plus a product-catalog gRPC lookup — architecturally unrelated to the search index. |
product-catalog |
Go | gRPC source for product detail (GetProductDetailsByIDs) and category metadata (CategoryQueryService.GetCategoriesByIDs, used by the filter schema, not by search). Also the publisher of the product.catalog.updated topic search-service indexes from. |
inventory-service |
Go | gRPC source for price/stock hydration (GetProductPricing) of the IDs search-service returns. Also the publisher of the inventory-search-event, stock-balance-status-changed, and sku-compliance-pricing-upserted topics search-service indexes from. |
ui-application (Mobile — Flutter) |
Flutter | features/dashboard/search/ (results grid + typeahead), features/dashboard/filter/ (filter sheet), features/dashboard/shop/shop_view.dart (search-bar entry point) — see Flutter wiring below. |
Catalog-to-search synchronization — four independent event streams
The product_search collection the Atlas Search query below runs against is never written synchronously — it’s built entirely from four independent, best-effort Pub/Sub streams out of product-catalog and inventory-service, documented in full in SR-006 FR-14–FR-18 and decided in ADR-00017.
| # | Producer → Topic | search-service subscription |
Ordering | Updates |
|---|---|---|---|---|
| 1 | product-catalog → product.catalog.updated |
product.catalog.updated-search-service |
None | Product lifecycle fields — create/basic-info/spec update/clone/publish/archive/delete (SR-006 FR-14) |
| 2 | inventory-service → inventory-search-event |
inventory-search-event-search-service |
None | Coarse inventory.price_min/price_max/total_stock/is_available (SR-006 FR-15) |
| 3 | inventory-service → stock-balance-status-changed |
stock-balance-status-changed-search-service |
Yes — keyed by product ID | Per-SKU is_in_stock/stock_status inside product_search.skus[] (SR-006 FR-16) |
| 4 | inventory-service → sku-compliance-pricing-upserted |
sku-compliance-pricing-upserted-search-service |
Yes — keyed by transaction ID | Per-SKU pricing/attribute rows inside product_search.skus[], status == "COMPLETED" events only (SR-006 FR-17) |
Stream 4’s topic is not exclusive to search-service — product-catalog’s own publish-readiness gate (ADR-00005) consumes the same sku-compliance-pricing-upserted topic via its own, separate subscription, for an unrelated purpose (marking a sync-readiness checkbox, not indexing). The two consumers never see each other’s ack/cursor state.
Each stream fails independently: a lost or delayed message on one never blocks the other three from updating (SR-006 FR-18), and none of the four publishers block or fail the admin-facing write that triggered them if the Pub/Sub publish itself errors (SR-006 NFR-06) — the trade-off is a bounded eventual-consistency window on search freshness (SR-006 NFR-03), not stronger consistency, with no publish-failure re-drive mechanism beyond Pub/Sub’s own retry today (Technical-Debt-00006, TD-06).
Inside search-service — the Atlas Search compound query
search-service’s internal/repository/product_search/product_search_crud_rep.go builds a MongoDB aggregation pipeline, not a plain find():
pipeline := mongo.Pipeline{
{{Key: "$search", Value: bson.D{
{Key: "index", Value: "product_search_index"},
{Key: "compound", Value: buildSearchCompound(tenantID, filter)},
}}},
{{Key: "$sort", Value: bson.D{{Key: "updated_at", Value: -1}}}},
{{Key: "$facet", Value: bson.D{
{Key: "data", Value: bson.A{
bson.D{{Key: "$skip", Value: filter.Offset}},
bson.D{{Key: "$limit", Value: filter.Limit}},
bson.D{{Key: "$project", Value: bson.D{{Key: "_id", Value: 1}}}},
}},
{Key: "count", Value: bson.A{bson.D{{Key: "$count", Value: "total"}}}},
}}},
}
buildSearchCompound assembles the compound operator’s clauses: a mandatory filter clause (tenant scoping — SR-006 NFR-02, plus published status), conditional must clauses per active category/gender/variant/price/discount filter, and — only when filter.Query is non-empty — a should clause block from textSearchShouldClauses, which scores title highest with fuzzy: {maxEdits: 1, prefixLength: 2} for typo tolerance (SR-006 FR-03), then tags, category.name, and description at lower weight. The result of this query is IDs and a total count only — SearchProductIDs never returns product fields, which is why GlobalSearchStrategy (see Architecture-00005’s Strategy section) must hydrate those IDs itself via product-catalog/inventory-service gRPC (SR-006 FR-04/FR-05) — the opposite of what search-service’s own “no request-time join needed” claim currently states; see Technical-Debt-00006.
The suggest/typeahead path — REST, bypassing GraphQL entirely
search-service exposes GET /client/api/v1/product/full-search (handler FullSearch, service method SuggestProducts), called directly by ui-application via Dio — not through shop-service’s GraphQL layer at all. It returns two independent kinds of suggestion: product-match rows, and demographic-scoped keyword rows (e.g. “dress for Women”) grouped from product_search.target_demographics via a $unwind+$group aggregation in product_demographic_suggest_rep.go — a separate query from SearchProductIDs, run against the same underlying collection.
The filter schema — an independently owned endpoint
shop-service’s GET /api/v1/filter/schema has no relationship to the Atlas Search index at all. Its service/filter package reads the admin-curated category_mapping collection first, joins the mapped leaf category IDs against product-catalog’s CategoryQueryService.GetCategoriesByIDs (name, slug, variant attributes) and shop-service’s own category-group image lookup, and wraps the result with a static config block (price/discount bounds, target demographics, sort options). This is why search filtering and the filter schema’s options must be kept consistent by convention (SR-006 FR-11), not by sharing a data source.
Flutter wiring — dashboard/search/, dashboard/filter/, dashboard/shop/shop_view.dart
shop/shop_view.dart— the Shop screen’s header search bar rendersSearchFilterBox/SearchFilterBoxControllerunder a'shop'-tagged instance. Typing here drives only the suggest call; tapping a suggestion, keyword, or the raw-query row callsShopController.selectSuggestion/selectKeyword/submitSearch, which navigate to the Search screen with the picked keyword (and, for a keyword suggestion, an auto-applied gender) passed viaGet.arguments.search/search_controller.dart—SearchScreenControlleris the generalized,sectionType-parameterized listing controllerArchitecture-00005already describes as the Strategy dispatch’s caller. Constructed withsectionType: nullfor global search, which is also what setsfilterable = true(enabling the filter sheet) and reads the incomingGet.argumentskeyword/filter payload ononInit._fetchPagecallsrepository.searchProducts(...)— the GraphQLsearchProductsquery — folding a keyword-suggestion’s demographic into the samegendersparameter the structured filter uses (SR-006 FR-10), never a separate field.search/widgets/search_filter_box_controller.dart— owns the typeahead’s REST-onlysuggestProductscall: 350ms debounce, 3-character minimum, populatingsuggestions/keywordSuggestionsindependently of the results grid (SR-006 FR-07–FR-09). Shared verbatim between the Shop screen’s'shop'-tagged instance and the Search screen’s'search'-tagged instance.filter/filter_controller.dart— loadsFilterRepository.getSchema()(the REST filter-schema endpoint above) on open, and builds aFilterResultPayloadon Apply.search_controller.dart’s_buildVariantAttributesreads the active filter group’s own attribute name (group.selectAttribute!.name/group.swatchAttribute!.name) when composing thevariantAttributessent tosearchProducts, rather than a hardcoded “Size”/“Color” string (SR-006 FR-13) — this is the one place the search query and the filter schema’s per-group naming have to agree, by convention rather than shared code.
End-to-end flow
- A shopper taps the Shop screen’s search bar (
shop_view.dart) or types directly on the Search screen (search_view.dart) — both render the sameSearchFilterBoxwidget under a screen-specific GetX tag. - Each keystroke (3+ characters) debounces 350ms into
search-service’s RESTSuggestProducts— product-match and demographic-keyword suggestions populate the dropdown; the results grid is untouched (SR-006 FR-07/FR-08). - Tapping a dropdown row, submitting the raw query, or (on the Shop screen) navigating with a picked keyword sets the active keyword/gender and calls
SearchScreenController.loadInitial(), firing the paginated GraphQLsearchProductsquery. shop-service’sproduct_search_svc.godispatches (via the Strategy registryArchitecture-00005documents) toGlobalSearchStrategy, which callssearch-service’sSearchProductIDsgRPC method.search-serviceruns the Atlas Search$search/compoundpipeline againstproduct_search_index, returning matched IDs, ranked and paginated via$skip/$limitinside a$facet(SR-006 FR-02/FR-06).GlobalSearchStrategyhydrates those IDs viaproduct-catalog’sGetProductDetailsByIDsandinventory-service’sGetProductPricing(gRPC), dropping any ID missing either counterpart (SR-006 FR-05).- The shopper opens the filter sheet (
filter/filter_view.dart); its schema comes fromshop-service’s independently-ownedGET /api/v1/filter/schema, not from search-service. Applying a filter callsSearchScreenController.applyFilters, re-running step 3 onward with the structured filter folded into the samecompound.mustclauses. - Once the paginated grid is exhausted,
SearchScreenController._loadTrailingSections()reuses the existingshopRepository.load(screenType: 'search')mechanism (the switch/map-dispatchArchitecture-00005documents, not the Strategy pattern) to append the same Top Products/New Arrivals/Just For You cross-sell sections every other screen uses.
Related Documents
- BRD-006 — Scalable Search Product
- SR-006 — Scalable Search Product System Requirements
- ADR-00005 — Event-Driven Catalog Synchronization — the
sku-compliance-pricing-upsertedtopic’s other, unrelated consumer - ADR-00007 — MongoDB Atlas Search for Product Search
- ADR-00017 — Independent Pub/Sub Streams for Catalog-to-Search Synchronization
- Technical Debt — Scalable Search Product Gaps
- Architecture: shop-service — Mobile Storefront Screen Delivery (GraphQL) — the
searchProductsStrategy dispatch this doc builds on - Microservices: search-service, shop-service, product-catalog, inventory-service
- Flutter walkthroughs: Search Box & Suggestions, Search Filter, Search Results