Catalog Service for Multi-Chain Grocery Delivery

Medium · System Design · Software Engineer · Other

Prompt

Design the catalog platform behind a multi-retailer grocery delivery marketplace. On the consumer app, a shopper selects a local supermarket branch, explores department aisles, runs keyword searches, builds a basket, and completes checkout, after which an in-store picker fulfills the order from physical shelves. Every storefront listing, search result card, and item detail view is served from this catalog, and both basket previews and final checkout rely on it for item pricing.

Account for the real-world characteristics of a multi-chain marketplace:

  • Hundreds of independent grocery chains participate on the platform, each operating many physical store branches.
  • Identical packaged goods—for instance, a 750 ml bottle of extra-virgin olive oil from the same brand—are sold across competing chains, while unit prices, promotional discounts, and shelf stock vary by individual branch.
  • Partner chains push product metadata, price changes, and inventory updates through scheduled bulk exports and incremental delta feeds on irregular cadences and with uneven data hygiene.

Clarifications & Boundaries

  • Traffic volume, freshness targets, and latency budgets are open for you to define; state concrete numbers and keep your architecture aligned with them.
  • Search ranking models, personalized recommendations, payment gateway processing, and picker routing are out of scope aside from their direct data contracts with the catalog.
  • Physical shelf stock is never perfectly observable; partner feeds only report what the retailer's own systems believe is on hand.
  • Establish clear positions on the following scoping questions up front:
    • Is browsing strictly scoped to one chosen branch at a time, or must shoppers also compare an item's price across nearby retailers?
    • How fresh must displayed prices and stock status be, and which price governs if an item's price shifts between basket addition and order checkout?
    • Do partner feeds supply valid universal barcodes (such as UPC/GTIN) on every SKU, or must your pipeline resolve and match items across chains?
    • How do you model variable-weight items (such as loose fruit or deli cuts) alongside multi-option product families (sizes and flavors)?
    • Roughly how many retail chains, store branches, and active SKUs per branch are you sizing for?

Scope & Expectations

  • Requirements & sizing: Propose realistic scale, read/write throughput, freshness SLAs, and checkout price-lock rules, covering barcodes, sold-by-weight goods, and product variants.
  • Data model & APIs: Separate shared product content from retailer- and branch-scoped pricing, promotions, and assortment state, and define clean customer, checkout, and partner APIs.
  • Feed ingestion & data hygiene: Design an ingestion and entity-matching pipeline that handles concurrent bulk snapshots and real-time deltas without letting stale or malformed feeds corrupt live listings.
  • Low-latency serving & consistency: Detail how branch-scoped browsing, keyword search, and authoritative checkout quotes achieve low latency and high availability at scale.

Step-by-step walkthrough

  1. Clarify requirements and core scoping assumptions

    A multi-chain grocery catalog has a messy, bursty write side (hundreds of independent retail chains sending uneven bulk exports and live deltas) and a latency-critical read side (millions of shoppers browsing aisles, searching, and checking out). Two structural principles anchor the design: partition data by how fast it changes and how widely it is shared, and follow a single price update end to end from partner feed to final checkout so nothing is dropped or applied out of order.

    Core scoping decisions

    1. Single-branch vs. cross-branch views: Browse, search, and basket flows are strictly scoped to one selected branch (the hot path). We also expose a lightweight cross-retailer price comparison ("view this item at up to 10 nearby branches") on the item detail screen.
    2. Freshness and checkout price rule: Incremental price/stock deltas appear in browse and search within 1 minute (p95); bulk snapshots finish within 15 minutes. Basket views display current prices, checkout re-prices every line from the authoritative price store and highlights any change for customer confirmation before payment, and placing the order freezes that quote. Weighted items freeze their price-per-kilogram at order placement and multiply by the actual weight scanned by the in-store picker.
    3. Barcodes vs. catalog matching: Packaged groceries usually carry a GTIN (Global Trade Item Number, the 8/12/13/14-digit barcode standard covering UPC and EAN codes), but partner feeds frequently contain typos, missing codes, chain-internal deli barcodes, or 4–5 digit PLU codes (Price Look-Up sticker numbers on loose produce, like 4131 for Fuji apples). Our ingestion pipeline must normalize, validate, and match items itself—while ensuring unmatched items are still immediately sellable using the partner's own text and photo.
    4. Weighted items and variants: Every item specifies sold_by (EACH or WEIGHT, with avg_unit_weight_g so carts can estimate totals). Variants (such as 16 oz vs. 32 oz or Vanilla vs. Plain) are distinct products linked by a shared family_id so the item page renders size/flavor pickers cleanly.
    5. Target scale and SLAs (proposed):
      • Supply: 1,000 retailers, 60,000 physical stores, 40,000 active items per store (2.4B store-item pairs).
      • Latency & availability: Browse/search p99 < 200 ms, item/cart batch lookup p99 < 100 ms, checkout quote p99 < 150 ms, read availability 99.95% (serving stays up on last-known-good data even if ingestion fails).
  2. Back-of-the-envelope scale and memory math

    Let us check row counts, write bursts, read fan-out, and memory sizes so every storage choice is grounded in numbers.

    Catalog & store cardinalities
      Retailers:               1,000
      Physical stores:         60,000  (chains of 1,000-2,000 stores down to local grocers)
      Store-item listings:     60,000 stores x 40,000 items = 2.4 billion pairs
      Retailer SKUs:           ~50M total (~50k avg per retailer; big chains ~150k)
      Canonical products:      ~5M shared + retailer-specific products
      Price lists (zones):     ~10,000 (chains price by regional zone; 10k x 40k = 400M prices)
    
    Write rates (ingestion)
      Product content edits:   ~200k/day (~2 writes/s)
      Price changes:           3% of 400M/day = 12M/day (~140/s avg; ~800k in one weekly-ad file)
      Inventory snapshots:     60k stores x 4 full files/day x 40k items = 9.6B rows/day ingested
                               Only ~5% actually changed -> 480M writes/day (~5.6k/s avg, ~50k/s peak)
    
    Read rates (customer traffic)
      Shopping sessions:       10M/day x 40 views/session = 400M views/day (~4.6k/s avg, ~15k/s peak)
      Item cards rendered:     15k peak views/s x 40 items/page = 600,000 item decorations/s!
      Search queries:          ~25% of views -> ~4,000 queries/s peak
      Checkout / cart quotes:  ~250 quotes/s peak x 40 cart lines = 10,000 strong price reads/s
    
    Storage & in-memory "Store Overlay" sizing
      Persistent stores:       products (5M x 5 KB = 25 GB), retailer SKUs (50M x 2 KB = 100 GB),
                               prices (400M x 100 B = 40 GB), availability (2.4B x 60 B = 144 GB)
      In-memory Store Overlay:
        - Stock bits:          60,000 stores x 50,000 SKUs x 3 bits (carried + 2-bit status) = ~1.13 GB
        - Zone price arrays:   10,000 price lists x 50,000 SKUs x 8 B (4B cents + 4B version) = 4.00 GB
        Total RAM across ALL 1,000 retailers = ~5.13 GB! (Largest 2,000-store chain = ~233 MB!)
    

    Three crucial architectural conclusions jump straight out of this math:

    1. Decorating 600,000 item cards/s cannot hit disk databases per item: Shared product content (25 GB) fits easily in a distributed cache, and all active prices and stock bits (~5.1 GB) fit right inside serving-node RAM as an event-updated store overlay.
    2. Diffing bulk inventory feeds is mandatory: Filtering unchanged rows drops 9.6B daily snapshot rows down to 480M real state transitions (20x write reduction).
    3. Never denormalize content into store-item rows: Copying a 5 KB product record across 2.4B store-item pairs would bloat storage to 12 TB and force 500M daily stock/price blips to rewrite heavyweight records.
  3. API design across customers, checkout, and retailers

    Customer read paths always start with store_id so the gateway routes each request directly to the serving cell holding that retailer's data.

    Customer Read APIs (scoped to one store, except nearby-offers)
      GET  /v1/stores/{store_id}/aisles
      GET  /v1/stores/{store_id}/aisles/{aisle_id}/items?limit=40&cursor=<token>
      GET  /v1/stores/{store_id}/search?q=olive+oil&filter=on_sale&sort=relevance|price&cursor=<token>
      GET  /v1/stores/{store_id}/products/{product_id}
      POST /v1/stores/{store_id}/products:batchGet          Body: {product_ids: [... up to 100]}
      GET  /v1/products/{product_id}/nearby-offers?lat=..&lng=..&limit=10
    
      Item card shape:
        {product_id, name, brand, size_text, image_url, sold_by: "EACH" | "WEIGHT",
         price: {unit_cents, per: "EACH" | "KG", promo: {promo_id, label, ends_at} | null,
                 price_version},
         availability: "IN_STOCK" | "LOW_CONFIDENCE" | "OUT_OF_STOCK"}
    
    Internal Checkout Quote APIs (strong consistency)
      POST /internal/v1/quotes
           Body: {store_id, lines: [{product_id, qty | est_weight_g}]}
           200:  {quote_id, valid_until,
                  lines: [{product_id, unit_cents, per, promo_id, price_version, orderable, reason}],
                  estimated_total_cents}
      GET  /internal/v1/quotes/{quote_id}                   (referenced immutably by placed order)
    
    Retailer Ingestion APIs
      POST /v1/retailers/{rid}/feeds
           Body: {type: "catalog"|"price"|"promo"|"inventory", mode: "full"|"delta",
                  scope_id, source_generated_at, file_url} -> 202 {feed_id}
      POST /v1/retailers/{rid}/updates                      Header: Idempotency-Key: <uuid>
           Body: {records: [{retailer_sku, scope_id, fields..., source_ts, source_seq}]} -> 202 {batch_id}
      GET  /v1/retailers/{rid}/feeds/{feed_id}
           200:  {status: "RECEIVED"|"PROCESSING"|"APPLIED"|"QUARANTINED",
                  rows_applied, rows_rejected, sample_errors}
    

    Notice two deliberate fields:

    • quote_id + valid_until: Freezes authoritative prices for up to 15 minutes (capped earlier if a promotion expires sooner) so checkout and order placement agree on every penny.
    • source_ts (retailer's event timestamp): Retailers send bulk files and real-time deltas concurrently; ordering updates by source_ts rather than network arrival time prevents a slow 02:00 nightly batch file from overwriting a 06:00 morning price change.
  4. Data model: split records by rate of change and sharing

    We separate the catalog into five narrow entities matched to how widely each fact is shared and how often it mutates:

      [1. Canonical Product]      P_204: "California Olive Ranch Extra-Virgin Olive Oil, 750 ml", photos, nutrition
             ^                    Shared across ALL retailers | Changes: weeks | ~5M rows (Postgres + Cache)
             | matched via GTIN / fuzzy model
      [2. Retailer SKU]           (Retailer=FreshMart, SKU=FM_910) -> P_204, dense_ordinal=318, aisle="Pantry"
             |                    Scoped to 1 retailer | Changes: days | ~50M rows (Postgres by retailer)
             +--------------------+-------------------------+
             v                                              v
      [3. Zone Price List]                           [5. Store Assortment & Availability]
      (List=Zone_7, SKU=FM_910) -> 899c, v19         (Store=S_84, SKU=FM_910) -> carried=1, IN_STOCK (p=0.96)
      Shared by ~6 stores | Changes: daily | ~400M   Scoped to 1 store | Changes: minutes | ~2.4B rows (KV)
             ^
      [4. Promotions]             (Promo=PR_4, Zone_7, FM_910) -> SALE 799c, UTC [start_at, end_at)
                                  Evaluated dynamically against wall-clock `now` at read time | ~1M rows
    

    Concrete schema layout:

    products        (product_id PK, gtins[], brand, title, size_val, size_unit, family_id,
                     sold_by EACH|WEIGHT, avg_unit_weight_g, images[], nutrition,
                     owner_retailer_id NULLABLE, content_version, updated_at)
    
    retailer_items  ((retailer_id, retailer_sku) PK, ordinal INT, product_id FK,
                     match_method GTIN|PLU|FUZZY|MANUAL|RETAILER_ONLY, match_confidence,
                     retailer_title, dept_path, last_seen_feed_id)
    
    stores          (store_id PK, retailer_id, lat, lng, timezone, price_list_id)
    
    prices          ((price_list_id, retailer_sku) PK, unit_cents, per EACH|KG|LB,
                     source_ts, source_seq, price_version, updated_at)
    
    promotions      (promo_id PK, retailer_id, scope_ids[], retailer_skus[],
                     kind SALE_PRICE|PCT_OFF|X_FOR_Y|BOGO, params_json, start_at_utc, end_at_utc)
    
    availability    ((store_id, retailer_sku) PK, carried BOOL, reported_status,
                     source_ts, found_prob FLOAT, served_status, updated_at)
    

    Why two subtle modeling choices pay off everywhere:

    • Unmatched items still get a product_id: When a new or store-brand SKU has no match yet, we mint a retailer-scoped product (owner_retailer_id = rid) from the retailer's text. Every downstream API, search query, and cart line works uniformly on product_id without null checks; if a match is found later, we redirect the SKU and alias the old ID.
    • Dense integer ordinal (0 .. N-1) per retailer: Lets the in-memory store overlay represent 50,000 items in a store as a contiguous 18.75 KB bitset (3 bits x 50,000) and a 400 KB price array (8 B x 50,000) instead of pointer-heavy hash tables!
  5. High-level architecture

    Ingestion and serving are decoupled through durable storage and CDC (Change Data Capture, which tails each database's commit log to publish Kafka change events reliably without dual-write race conditions):

      Retailers                                                  Customers (Mobile / Web)
        |-- Bulk CSV/JSON/XML --> [ Raw Object Store (S3) ]                 |
        |-- Real-time Deltas ---> [ Intake API ]                            v
                                        |                           [ API Gateway ] ---> [ Image CDN ]
                                        v                                   |
                 [ Kafka Raw: bulk-lane | delta-lane ]          +-----------+-----------+
                                        |                       v           v           v
                                        v                 [Browse Svc] [Search Svc] [Quote Svc]
                 [ Normalizer (units, zones, cents) ]           |           |   |       |
                                        |                       |           |   v       |
                                        v                       |           | [Search Index ]
                 [ Validator ] ---> [ Quarantine + Ops UI ]     |           | [1 doc per    ]
                                        |                       |           | [retailer SKU ]
                                        v                       v           v     ^     |
                 [ Product Matcher ] -> [ Human Review Q ] [ In-Memory Store Overlay ]  |
                                        |                  [ + Product Content Cache ]  |
                                        v                       ^                 |     |
                 [ Conditional State Writers (CAS) ]            |            [Indexer]  |
                                        |                       |                 ^     |
                                        v                       |                 |     |
       [ Postgres (Products/SKUs) | KV Store (Prices/Stock) ] <-+-----------------+-----+
                                        |                       |                 |  (strong read
                                        +--- CDC Kafka Events --+-----------------+   for quotes)
    
       [ Picker App Scans (Found / Not Found) ] ---> [ Availability ML Scorer ] --^
    
  6. Deep dive 1: ingesting, validating, and matching messy retailer feeds

    Every retailer feed passes through six idempotent stages:

    1. Land immutably: Save the raw file or batch in S3 keyed by (retailer_id, content_sha256) so duplicate uploads are skipped and parser bugs can be replayed from raw files.
    2. Separate fast and slow lanes: Route real-time deltas to raw-deltas and multi-million-row files to raw-bulk with independent consumer pools, ensuring a 40M-row chain inventory dump never delays a single urgent price fix.
    3. Normalize: Apply per-retailer config to parse units ("25.4 FL OZ" -> 750 ml), convert dollar strings to integer cents, and convert local promotion times to UTC.
    4. Validate (row + batch guardrails):
      • Row rules: Reject price <= 0 or price > 20x category p99; hold single-item drops/spikes > 50% vs. previous price for review while keeping the old price live.
      • Batch quarantine: If > 1% of rows fail or price drops exceed 5x the retailer's normal rate, quarantine the entire batch and page ops.
      • Snapshot completeness guard: In a full inventory snapshot, omitted items normally mean "out of stock." If a truncated file has < 90% of the store's usual SKU count or would remove > 20% of active items, apply the rows present as updates, skip implicit removals, and alert.
    5. Diff: Drop the ~95% of inventory snapshot rows whose status has not changed before hitting storage.
    6. Match to canonical products (precision over recall): Showing the wrong photo/size ships the wrong grocery item to a customer, whereas missing a match merely displays the retailer's own plain text. We match in three tiers:
      • Tier 1 (Validated GTIN barcode): Verify formatting, modulo-10 check digit (the final checksum digit that catches single-digit typos), and exclude GS1 restricted-circulation prefixes (in-store random-weight meat/deli/coupon codes starting with 02, 04, or 2 in 13-digit EAN form, or 0/2 in 8-digit form, which mean totally different items at different chains!).
      • Tier 2 (PLU codes): Map standard 4-digit (4131) and 5-digit organic (94131) produce codes to weighted produce items.
      • Tier 3 (Fuzzy ML model + human review): Block candidates by (normalized_brand, normalized_size, category); auto-merge above a 99%-precision score threshold, queue mid-confidence popular items for human review, and mint a retailer-only product otherwise.
    from typing import Optional
    
    
    def normalize_gtin(raw_code: str) -> Optional[str]:
        """Validate and pad a UPC/EAN/GTIN barcode to 14 digits, or return None if unusable."""
        # Allow spaces and hyphens, but reject alphanumeric internal SKUs like "SKU-12345678"
        cleaned = raw_code.strip().replace(" ", "").replace("-", "")
        if not cleaned.isdigit() or len(cleaned) not in (8, 12, 13, 14):
            return None
    
        # Reject 8-digit store-internal restricted circulation barcodes (GS1 RCN-8: 0xx, 2xx)
        if len(cleaned) == 8 and cleaned.startswith(("0", "2")):
            return None
    
        gtin14 = cleaned.zfill(14)
    
        # Verify standard GS1 modulo-10 check digit (weights alternate 3, 1 from right to left)
        weighted_sum = 0
        for idx, digit_char in enumerate(reversed(gtin14[:-1])):
            weight = 3 if idx % 2 == 0 else 1
            weighted_sum += int(digit_char) * weight
        expected_check_digit = (10 - (weighted_sum % 10)) % 10
        if expected_check_digit != int(gtin14[-1]):
            return None
    
        # Reject 12/13/14-digit in-store random-weight & loyalty prefixes (EAN-13 02x, 04x, 2xx)
        ean13_body = gtin14[1:]
        if ean13_body.startswith(("02", "04", "2")):
            return None
    
        return gtin14
    
  7. Deep dive 2: tracing one price update end to end

    Let us trace a 750 ml bottle of extra-virgin olive oil in Pricing Zone 7 changing from $8.49 (849 cents) to $8.99 (899 cents) at 07:00:00, and verify every place it could be delayed, lost, or applied out of order:

    07:00:00  Retailer POS sets price = $8.99 (record carries source_ts = 07:00:00, seq = 1)
    07:02:00  Retailer calls POST /updates (2 min retailer-side batching lag)
      +50 ms  Intake API validates schema, writes to Kafka `raw-deltas` (acks=all), returns 202
      +0.4 s  Normalizer maps zone -> price_list_id=7, "$8.99" -> 899 cents
      +0.3 s  Validator checks +5.9% delta (< 50% hold threshold) -> passes
      +0.2 s  Price Writer reads stored row (849c, source_ts=last week, price_version=18),
              performs compare-and-swap write -> (899c, source_ts=07:00:00, price_version=19)
      +0.3 s  Price KV store's CDC log publishes v19 to Kafka `price-changes` (key=price_list_id)
      +0.8 s  Serving nodes for this retailer consume v19 and update RAM overlay slot[318] = (899, 19)
      ------
      07:02:02 (~2 s after intake, well within 1-min SLA):
        - Search & aisle pages read overlay slot[318] -> display $8.99
        - Checkout POST /quotes does a strong quorum read on Price KV -> locks $8.99 (v19)
    

    How we defeat every failure mode along this path:

    • Out-of-order bulk vs. delta updates: Suppose a slow 03:00:00 bulk price file finishes parsing at 07:05:00 (after the 07:00:00 delta!). Our writer uses optimistic concurrency control (compare-and-swap on price_version): it compares (change.source_ts, change.source_seq) against the stored row, sees 03:00:00 <= 07:00:00, and ignores the stale bulk row! And to stop a broken retailer clock stamped 2099-01-01 from blocking all future updates forever, timestamps > 10 minutes ahead of server wall clock are rejected to quarantine.
    • No lost overlay updates on worker crash: Notice why price-changes is emitted by the database's CDC/outbox log, not by the Python/Go worker after writing! If the worker crashed right after updating prices to v19 and before publishing to Kafka, the retried Kafka message would see 07:00:00 <= 07:00:00 (IGNORED_OLDER) and never publish the event—leaving the RAM overlay stuck at $8.49! Emitting from CDC guarantees every committed write reaches the overlay, and the overlay ignores out-of-order replays by checking event.price_version > slot.price_version.
    MAX_CLOCK_SKEW_SECONDS = 600
    
    
    def apply_price_update(price_store, change, now_epoch_s: int) -> str:
        """Conditionally apply a price update only if its retailer timestamp is newer."""
        # Guard against a misconfigured future retailer clock poisoning future updates
        if change.source_ts > now_epoch_s + MAX_CLOCK_SKEW_SECONDS:
            return "REJECTED_FUTURE_CLOCK"
    
        current = price_store.get(change.price_list_id, change.retailer_sku)
        if current is not None:
            if (change.source_ts, change.source_seq) <= (current.source_ts, current.source_seq):
                return "IGNORED_STALE"
            next_version = current.price_version + 1
            expected_version = current.price_version
        else:
            next_version = 1
            expected_version = None
    
        # Atomic compare-and-swap prevents two concurrent workers from clobbering each other
        committed = price_store.put_if_version(change, next_version, expected_version)
        if not committed:
            return "RETRY_CAS_CONFLICT"
        return "APPLIED"
    

    Exact-second promotions without midnight write storms: Rather than running a batch job at 00:00:00 to overwrite thousands of base prices when a sale starts or ends, promotions are preloaded into the store overlay hours ahead with UTC [start_at_utc, end_at_utc) timestamps and evaluated on the fly during reads and quotes (start_at_utc <= now < end_at_utc).

  8. Deep dive 3: store-scoped browse, search, and the in-memory overlay

    Where should per-store prices and availability sit relative to the inverted search index (the text search engine mapping query words like "olive oil" to matching items)? Compare the two architectures:

    Metric Option A: 1 search doc per (store, item) Option B: 1 search doc per retailer_sku + RAM Overlay
    Search index size 2.4B docs (~2.4 TB) 50M docs (~100 GB, 48x smaller)
    Daily price/stock re-indexes ~550M full Lucene doc rewrites/day (50k/s peaks) 0 (RAM overlay updates in ~1 s from Kafka)
    Popular product photo edit Rewrites up to 60,000 docs Rewrites 1 doc per retailer carrying it
    Price sort & stock filter Native inside search engine Performed in Search Svc over top <= 2,000 candidate ordinals

    We choose Option B: slow-changing text and store-assortment membership (carried_store_ids) live in the 50M-document search index routed by retailer_id, while fast-changing prices, promotions, and stock bits live in the ~5.1 GB RAM overlay partitioned into retailer cells (each serving pod in a cell holds its assigned retailers' overlays—at most ~233 MB even for a 2,000-store chain—and snapshots to S3 every 10 minutes for fast restarts).

    How a customer search (GET /v1/stores/84/search?q=olive+oil&limit=40) executes in ~55 ms:

    1. Resolve Store 84 -> Retailer R, Price List 7, Overlay Cell C         (< 0.1 ms, in memory)
    2. Query Retailer R's search shard: match("olive oil") AND store_ids=84
       -> returns top 120 (3 x limit) dense SKU ordinals + product_ids      (35-45 ms)
    3. Check Store 84's 3-bit RAM availability array for those 120 ordinals:
       drop OUT_OF_STOCK items (fetch next batch if < 40 remain)            (< 0.5 ms)
    4. Multi-get top 40 product_ids from local LRU / Redis content cache,
       and read effective_price(now) from Price List 7's RAM array          (~5 ms)
    

    For sort=price or filter=on_sale, the service fetches up to 2,000 matching (ordinal, product_id) pairs from the retailer's search shard (IDs only), evaluates their live overlay prices in < 1 ms, and sorts in memory. Aisle browse pages skip the search engine completely: they slice a precomputed popularity-ordered ordinal list for (retailer_id, aisle_id) against Store 84's overlay bitset in < 25 ms total.

  9. Scaling, failure handling, and trade-off summary

    Scaling bottlenecks

    • 600k item decorations/s & viral products: Handled horizontally by adding stateless read replicas to each retailer's overlay cell, backed by a 2-tier product content cache (25 GB Redis cluster + per-pod in-memory LRU for hot items like holiday staples) and content-hashed CDN URLs for images.
    • 50k/s morning inventory spikes & weekly ad switches: Absorbed by the dedicated raw-bulk Kafka lane, diff filtering (dropping 95% unchanged rows), and partitioning the availability KV store by store_id and price KV store by price_list_id.
    • Multi-region serving: Active-active read regions each run their own search replicas and RAM overlays fed by cross-region Kafka replication; checkout quotes read regionally replicated price KV stores with bounded staleness checks.

    Failure handling

    • Ingestion pipeline outage: Customer browse, search, and checkout stay 100% online on the last accepted catalog state while raw files buffer safely in S3.
    • Overlay Kafka lag (> 30 s): Triggers an alert, while checkout remains completely accurate because POST /internal/v1/quotes reads the authoritative Price KV store directly rather than the overlay.
    • Price KV store degraded: POST /internal/v1/quotes may fall back to the RAM overlay only if that pod's Kafka lag is < 15 s; otherwise checkout fails closed with a retryable error rather than under- or over-charging.
    • Synthetic canary monitoring: A continuous canary updates a hidden test SKU's price every 60 seconds and verifies search visibility and quote accuracy end-to-end.

    Summary of key trade-offs

    • 5-way normalized storage + read-time overlay join avoids rewriting 2.4B bloated records on daily stock/price churn, trading disk denormalization for a sub-millisecond RAM array lookup at read time.
    • 50M retailer-SKU search index + 5.1 GB RAM overlay shrinks the search cluster 48x and eliminates 550M daily re-indexes, at the acceptable trade-off of sorting price queries over the top 2,000 relevant candidates in the service layer.
    • Eventually consistent browse (~2 s) + strongly consistent checkout quotes keeps browse/search ultra-fast and resilient while guaranteeing honest, auditable order totals.
    • source_ts conditional writes + batch quarantine protect customers from out-of-order batch files and broken $0.00 feeds, prioritizing price integrity over blind millisecond ingestion.

Intuition & how it works

Think of a multi-chain grocery catalog like printing menus for 60,000 local branches using one shared laminated photo book plus a thin transparent sticker sheet per branch. A 750 ml bottle of extra-virgin olive oil carries the exact same bottle photo, nutrition facts, and volume everywhere in the country, and those facts barely change all year—so we store them once in the shared photo book (canonical product content). Meanwhile, whether Branch 84 currently has that bottle on the shelf changes every hour, and Pricing Zone 7's price changes every week—so each branch keeps a compact in-memory overlay (just 3 bits of stock status per item and an 8-byte price slot per pricing zone) that our servers lay right on top of the shared photo book in microseconds when rendering a page.

A naive design that stores product descriptions, photos, prices, and stock together in one giant (store_id, product_id) table and search index collapses under write amplification. With 60,000 stores carrying 40,000 items each (2.4 billion store-item pairs), retailers generate ~500 million stock and price updates per day; rewriting multi-kilobyte records and re-indexing search documents on every stock change would overwhelm both databases and search clusters, while fixing one typo on a popular cereal box would require updating 60,000 rows.

Trace 4 concrete steps for 750 ml Extra-Virgin Olive Oil (P_204) sold at Retailer R's Store 84 (in Pricing Zone 7) to see the pieces work together:

  1. Ingest & match: Retailer R uploads SKU FM_910 with barcode "850687002039". The pipeline verifies the barcode's check digit (the final checksum digit that catches typos), links (R, FM_910) -> P_204 at dense index ordinal = 318, and indexes 1 search document for (R, FM_910).
  2. Apply a price change safely: At 07:00, Retailer R sends a delta changing Zone 7's price for FM_910 from 849 cents to 899 cents (source_ts = 07:00). Using optimistic concurrency control (updating the row only if its version has not changed underneath us), the price writer confirms 07:00 is newer than the stored timestamp, updates (Zone_7, FM_910) to 899 cents (price_version = 19), and streams v19 from the database's CDC log (Change Data Capture commit stream) into Retailer R's in-memory store overlay within ~2 seconds.
  3. Serve a customer search: When a customer searches "olive oil" in Store 84, the search service queries Retailer R's small search index for candidate ordinals carried by Store 84, checks Store 84's RAM bitset (ordinal 318 is IN_STOCK) and Zone 7's RAM price array (899 cents), and fetches P_204's cached photo and title—returning 40 rich cards in ~55 ms.
  4. Lock the price at checkout: While browse pages use eventual consistency (reading the RAM overlay, which can lag by 1–2 seconds), checkout calls POST /internal/v1/quotes, which performs a strongly consistent read directly against the authoritative price store, highlights the 849 -> 899 cent change if the bottle was added to the basket earlier, and freezes 899 cents (price_version = 19) on the placed order.

Key trade-offs

  • Normalized 5-layer model + read-time join vs. one denormalized (store, item) record. Splitting canonical products (5M), retailer SKUs (50M), zone prices (400M), promotions (1M), and store availability (2.4B) means every stock or price update mutates a tiny narrow row and never invalidates shared product caches. The trade-off is joining content + price + stock on every read, which stays sub-millisecond because 25 GB of product content sits in cache and all active prices and stock bits (~5.1 GB total across all 60,000 stores) sit in serving-node RAM.
  • Retailer-SKU search index (50M docs) + RAM overlay vs. store-item search index (2.4B docs). Indexing one document per retailer SKU shrinks the search cluster 48x and eliminates ~550M daily Lucene document rewrites from price and stock churn. In exchange, sort=price and filter=on_sale cannot execute natively inside the search index; the search service fetches up to 2,000 matching SKU IDs from the index and sorts/filters them against the RAM overlay in < 1 ms (making ultra-broad price-sorted queries approximate past the top 2,000 relevant items).
  • Eventually consistent browse/search vs. strongly consistent checkout quotes. Serving 600,000 item card decorations/s from RAM overlays keeps p99 latency low and insulates browsing from database spikes, while performing strong reads (10,000 line reads/s at peak) only on cart/checkout quotes guarantees customers never pay an outdated price without seeing and confirming it.
  • Locking prices at order placement (via expiring quotes) vs. at add-to-cart or in-store picking. Locking at add-to-cart would force retailers to honor week-old sale prices in abandoned carts, whereas pricing at physical picking hours later would charge customers more than they agreed to pay. Re-quoting visibly at checkout and freezing that quote on order placement (charging locked_price_per_kg * scanned_weight for weighted produce) is fair and auditable.
  • Ordering updates by retailer source_ts vs. server arrival time. Comparing source_ts prevents a delayed 02:00 bulk file from clobbering a 06:00 real-time delta and makes retries idempotent, at the cost of having to quarantine records whose misconfigured retailer clocks lie more than 10 minutes in the future.
  • High-precision product matching (~99% precision) vs. aggressive auto-merging. Requiring validated barcodes or high ML confidence leaves some ambiguous SKUs as plain retailer-only products until human review, which is far safer than falsely merging 16 oz and 32 oz jars and delivering the wrong item.

Common mistakes

  • Putting product descriptions, prices, and inventory into a single (store_id, product_id) database row or search document, turning half a billion daily stock and price updates into massive write and re-indexing storms.
  • Applying bulk snapshots and real-time deltas in arrival order (or sharing one FIFO queue between 40M-row bulk files and urgent single-item deltas), causing stale files to overwrite newer prices and delaying live fixes by hours.
  • Publishing Kafka invalidation events from application code after writing to the price database, where a worker crash between the DB commit and Kafka publish causes the retry to be skipped as "not newer" and leaves the in-memory overlay permanently stale; always publish from an outbox or CDC log.
  • Treating omitted rows in a full inventory file as "out of stock" without a completeness threshold, allowing a single truncated retailer export to wipe out 90% of a store's catalog.
  • Matching barcodes blindly across retailers without verifying the modulo-10 check digit, rejecting alphanumeric SKU strings, or filtering out GS1 restricted-circulation prefixes (02x, 04x, 2xx) that each chain assigns independently to random-weight deli and meat packages.
  • Flipping sale prices via a midnight batch write job, creating huge traffic spikes and late transitions instead of preloading promotion [start_at_utc, end_at_utc) windows and evaluating effective_price(now) dynamically on reads.
  • Serving checkout totals from the same eventually consistent cache as browse pages, or conversely hitting disk databases 600,000 times per second to render browse grids.

Follow-up questions

  • Suppose a partner's ingestion file accidentally overwrites thousands of item prices to $0.00. How do you prevent those bad prices from reaching shoppers? Three independent defense layers block bad prices before they reach shoppers. First, row-level ingestion validation immediately rejects any price <= 0 and holds any single-item price drop exceeding 50% (compared against both its previous accepted price and the median across the retailer's other zones) while keeping the old price live. Second, batch-level anomaly detection quarantines the entire feed file or update batch whenever more than 1% of rows fail validation or the fraction of price drops spikes above 5x that retailer's historical baseline, paging operations with a one-click review UI in case of a legitimate clearance event. Third, as a final circuit breaker at checkout, the quote service refuses to mark any cart line orderable if its effective price falls below a hard safety floor (such as 20% of its 30-day rolling median).
  • How would you support branch-specific promotional discounts that activate and expire on exact timestamps? Ingest each promotion with its target store_ids (or price_list_ids), item ordinals, discount rule (SALE_PRICE, PCT_OFF, X_FOR_Y, BOGO), and exact start_at_utc / end_at_utc converted from each branch's local time zone. Preload upcoming promotions into both the price store and the in-memory store overlay hours ahead of time, and compute effective_price(base_cents, promos, now) dynamically on every read and checkout quote using NTP-synchronized server clocks—so sales turn on and off at the exact second with zero midnight write bursts! To keep checkout consistent across boundaries, cap every quote's valid_until at min(now + 15m, next_promo_boundary_of_cart_items) so an order placed at 23:59:58 honors the active sale while a checkout completed at 00:00:05 cleanly re-quotes at the post-sale price.
  • Shoppers frequently buy items marked in stock that in-store pickers fail to locate on the shelf. How can picker fulfillment events improve stock accuracy? Every in-store pick generates a real-time ground-truth label (found scan vs. not_found stockout) stamped with (store_id, retailer_sku, timestamp). Combine a fast reactive rule—for example, two not_found scans for the same item at the same branch within 3 hours immediately downgrade served_status to LOW_CONFIDENCE or OUT_OF_STOCK until the next restock feed—with a gradient-boosted P(found) model trained on partner-reported stock/quantity, feed staleness, recent branch-item pick outcomes, item velocity, and time-of-day/day-of-week restock patterns. Because hiding items creates censoring bias (an item hidden as OUT_OF_STOCK is never ordered, so we never observe when shelves are restocked until the next file!), keep borderline items visible with a "Low stock" badge + substitution prompt, decay penalties at typical morning restock hours, and tune thresholds via A/B tests balancing found-rate against gross merchandise value (GMV).
  • What is your onboarding strategy when a newly signed retail chain provides zero universal barcodes in its product feed? Decouple branch launch from cross-retailer deduplication so onboarding never blocks on missing barcodes: normalize the chain's names, brands, parsed package sizes, categories, and photos, and immediately mint a retailer-scoped product_id (owner_retailer_id = new_rid) for any unmatched SKU so 100% of their catalog is searchable and orderable on day one. In parallel, run our fuzzy ML matcher blocked on (normalized_brand, normalized_size, category): auto-link pairs scoring above our 99%-precision threshold, route medium-confidence high-volume items to human reviewers first, and leave long-tail items as retailer-only products. Once orders begin flowing, harvest ground-truth barcodes directly from the physical UPCs that in-store pickers scan during fulfillment (requiring N consistent picker scans at that chain before auto-linking) to steadily enrich and merge the catalog over time.

Follow-up questions

Similar questions

More RapidSOS interview questions

All 1 RapidSOS questions →