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 mlbottle 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
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
- 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.
- 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.
- 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
4131for 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. - Weighted items and variants: Every item specifies
sold_by(EACHorWEIGHT, withavg_unit_weight_gso carts can estimate totals). Variants (such as16 ozvs.32 ozorVanillavs.Plain) are distinct products linked by a sharedfamily_idso the item page renders size/flavor pickers cleanly. - Target scale and SLAs (proposed):
- Supply:
1,000retailers,60,000physical stores,40,000active items per store (2.4Bstore-item pairs). - Latency & availability: Browse/search p99
< 200 ms, item/cart batch lookup p99< 100 ms, checkout quote p99< 150 ms, read availability99.95%(serving stays up on last-known-good data even if ingestion fails).
- Supply:
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:
- 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. - Diffing bulk inventory feeds is mandatory: Filtering unchanged rows drops
9.6Bdaily snapshot rows down to480Mreal state transitions (20xwrite reduction). - Never denormalize content into store-item rows: Copying a
5 KBproduct record across2.4Bstore-item pairs would bloat storage to12 TBand force500Mdaily stock/price blips to rewrite heavyweight records.
- Decorating 600,000 item cards/s cannot hit disk databases per item: Shared product content (
API design across customers, checkout, and retailers
Customer read paths always start with
store_idso 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 bysource_tsrather than network arrival time prevents a slow02:00nightly batch file from overwriting a06:00morning price change.
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 rowsConcrete 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 onproduct_idwithout 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 represent50,000items in a store as a contiguous18.75 KBbitset (3 bits x 50,000) and a400 KBprice array (8 B x 50,000) instead of pointer-heavy hash tables!
- Unmatched items still get a
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 ] --^Deep dive 1: ingesting, validating, and matching messy retailer feeds
Every retailer feed passes through six idempotent stages:
- 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. - Separate fast and slow lanes: Route real-time deltas to
raw-deltasand multi-million-row files toraw-bulkwith independent consumer pools, ensuring a 40M-row chain inventory dump never delays a single urgent price fix. - 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. - Validate (row + batch guardrails):
- Row rules: Reject
price <= 0orprice > 20xcategory 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 exceed5xthe retailer's normal rate, quarantine the entire batch and page ops. - Snapshot completeness guard: In a
fullinventory 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.
- Row rules: Reject
- Diff: Drop the ~95% of inventory snapshot rows whose status has not changed before hitting storage.
- 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, or2in 13-digit EAN form, or0/2in 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 a99%-precision score threshold, queue mid-confidence popular items for human review, and mint a retailer-only product otherwise.
- 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
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- Land immutably: Save the raw file or batch in S3 keyed by
Deep dive 2: tracing one price update end to end
Let us trace a
750 mlbottle of extra-virgin olive oil in Pricing Zone 7 changing from$8.49(849cents) to$8.99(899cents) at07: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:00bulk price file finishes parsing at07:05:00(after the07:00:00delta!). Our writer uses optimistic concurrency control (compare-and-swap onprice_version): it compares(change.source_ts, change.source_seq)against the stored row, sees03:00:00 <= 07:00:00, and ignores the stale bulk row! And to stop a broken retailer clock stamped2099-01-01from blocking all future updates forever, timestamps> 10 minutesahead of server wall clock are rejected to quarantine. - No lost overlay updates on worker crash: Notice why
price-changesis emitted by the database's CDC/outbox log, not by the Python/Go worker after writing! If the worker crashed right after updatingpricestov19and before publishing to Kafka, the retried Kafka message would see07: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 checkingevent.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:00to 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).- Out-of-order bulk vs. delta updates: Suppose a slow
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 OverlaySearch index size 2.4Bdocs (~2.4 TB)50Mdocs (~100 GB, 48x smaller)Daily price/stock re-indexes ~550Mfull Lucene doc rewrites/day (50k/speaks)0(RAM overlay updates in ~1 s from Kafka)Popular product photo edit Rewrites up to 60,000docsRewrites 1doc per retailer carrying itPrice sort & stock filter Native inside search engine Performed in Search Svc over top <= 2,000candidate ordinalsWe choose Option B: slow-changing text and store-assortment membership (
carried_store_ids) live in the50M-document search index routed byretailer_id, while fast-changing prices, promotions, and stock bits live in the~5.1 GBRAM overlay partitioned into retailer cells (each serving pod in a cell holds its assigned retailers' overlays—at most~233 MBeven 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=priceorfilter=on_sale, the service fetches up to2,000matching(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 mstotal.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 GBRedis 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-bulkKafka lane, diff filtering (dropping 95% unchanged rows), and partitioning the availability KV store bystore_idand price KV store byprice_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 becausePOST /internal/v1/quotesreads the authoritative Price KV store directly rather than the overlay. - Price KV store degraded:
POST /internal/v1/quotesmay 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.4Bbloated 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
48xand eliminates550Mdaily re-indexes, at the acceptable trade-off of sorting price queries over the top2,000relevant 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_tsconditional writes + batch quarantine protect customers from out-of-order batch files and broken$0.00feeds, prioritizing price integrity over blind millisecond ingestion.
- 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 (
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:
- Ingest & match: Retailer R uploads SKU
FM_910with barcode"850687002039". The pipeline verifies the barcode's check digit (the final checksum digit that catches typos), links(R, FM_910) -> P_204at dense indexordinal = 318, and indexes 1 search document for(R, FM_910). - Apply a price change safely: At
07:00, Retailer R sends a delta changing Zone 7's price forFM_910from849cents to899cents (source_ts = 07:00). Using optimistic concurrency control (updating the row only if its version has not changed underneath us), the price writer confirms07:00is newer than the stored timestamp, updates(Zone_7, FM_910)to899cents (price_version = 19), and streamsv19from the database's CDC log (Change Data Capture commit stream) into Retailer R's in-memory store overlay within ~2 seconds. - 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 318isIN_STOCK) and Zone 7's RAM price array (899cents), and fetchesP_204's cached photo and title—returning 40 rich cards in ~55 ms. - 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 the849 -> 899cent change if the bottle was added to the basket earlier, and freezes899cents (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 because25 GBof product content sits in cache and all active prices and stock bits (~5.1 GBtotal across all 60,000 stores) sit in serving-node RAM. - Retailer-SKU search index (
50Mdocs) + RAM overlay vs. store-item search index (2.4Bdocs). Indexing one document per retailer SKU shrinks the search cluster 48x and eliminates ~550Mdaily Lucene document rewrites from price and stock churn. In exchange,sort=priceandfilter=on_salecannot execute natively inside the search index; the search service fetches up to2,000matching 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,000line 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_weightfor weighted produce) is fair and auditable. - Ordering updates by retailer
source_tsvs. server arrival time. Comparingsource_tsprevents a delayed02:00bulk file from clobbering a06:00real-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 merging16 ozand32 ozjars 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
fullinventory 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 evaluatingeffective_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 <= 0and holds any single-item price drop exceeding50%(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 than1%of rows fail validation or the fraction of price drops spikes above5xthat 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 lineorderableif its effective price falls below a hard safety floor (such as20%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(orprice_list_ids), item ordinals, discount rule (SALE_PRICE,PCT_OFF,X_FOR_Y,BOGO), and exactstart_at_utc/end_at_utcconverted 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 computeeffective_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'svalid_untilatmin(now + 15m, next_promo_boundary_of_cart_items)so an order placed at23:59:58honors the active sale while a checkout completed at00:00:05cleanly 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 (
foundscan vs.not_foundstockout) stamped with(store_id, retailer_sku, timestamp). Combine a fast reactive rule—for example, twonot_foundscans for the same item at the same branch within 3 hours immediately downgradeserved_statustoLOW_CONFIDENCEorOUT_OF_STOCKuntil the next restock feed—with a gradient-boostedP(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 asOUT_OF_STOCKis 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 our99%-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
- 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?
- How would you support branch-specific promotional discounts that activate and expire on exact timestamps?
- 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?
- What is your onboarding strategy when a newly signed retail chain provides zero universal barcodes in its product feed?
Similar questions
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency
- Multi-Source Enterprise Question Answering System