Merchant Snapshot Catalog with Admin Attribute Overrides

Medium · System Design · Software Engineer · Onsite

Prompt

Architect a multi-merchant product catalog service where merchants upload full-catalog snapshot files, shoppers browse items at low latency, and internal administrators apply attribute-level overrides.

Use the following baseline requirements:

  • Snapshot ingestion: Each upload contains a merchant's entire product assortment rather than incremental deltas. Across 50,000 merchants, catalog size averages 20,000 items per merchant while the median merchant carries just 50 items. Multi-version snapshot isolation is unnecessary—while an upload applies item by item, concurrent reads may observe some updated products alongside not-yet-updated ones.
  • Shopper read traffic: 50 million shoppers drive 11,000 read queries per second with a 400 ms latency budget across two operations: listing all active SKUs for a retailer_id and fetching full item details by product_id.
  • Administrator overrides: Platform admins may override any attribute on any item globally. Future merchant snapshots must never clobber an active override, yet a merchant omitting an item from a snapshot still removes that item from shopper view even if overrides exist on it. Whenever an admin deletes an override, reads must immediately surface the merchant's most recently uploaded value for that attribute.

Walk through the initial architecture and four progressive extensions:

  • Part 1 — Core architecture: Define schemas, database/caching choices, ingestion flow, and read endpoints that uphold every override rule at 11,000 QPS within 400 ms despite extreme merchant size skew.
  • Part 2 — Snapshot diffing: Explain how inserted, removed, modified, and unchanged items are identified, what baseline state a new upload compares against (especially if an earlier job stopped mid-way), how canonical normalization filters formatting noise, and the memory/CPU cost on multi-million-SKU catalogs.
  • Part 3 — Superseding a bad upload: Suppose a merchant uploads Snapshot 1 by mistake and rapidly submits corrective Snapshot 2—before, during, or after Snapshot 1 runs. Guarantee the catalog converges to Snapshot 2's exact state (preserving overrides on restored items) regardless of worker timing.
  • Part 4 — Onboarding 50,000 daily merchants: Estimate rows scanned versus rows written when 50,000 additional merchants join and upload daily snapshots, and scale upload ingestion, workers, and storage while keeping 50-item shops insulated from giant catalogs.
  • Part 5 — Observability and data integrity: Specify read and freshness SLOs, automated verification that applied catalog state matches uploaded files, alerting, distributed tracing, and an immutable override audit trail.

Scope & Expectations

  • Clarify key identifier and pagination contracts (product_id vs. (retailer_id, sku), tombstone retention, and cursor pagination for multi-million-SKU listings).
  • Design a conflict-free data model and sharded storage/caching layer where merchant snapshots and admin overrides never overwrite each other.
  • Provide bounded-memory diffing, database-fenced snapshot ordering, size-tiered worker isolation for 200,000x catalog skew, and end-to-end catalog correctness checks.

Step-by-step walkthrough

  1. Clarify requirements and pin down the invariants

    Every open clarifying question in the prompt directly shapes the schema and sharding strategy, so state concrete, well-reasoned assumptions up front:

    • How product_id relates to retailer_id and sku: a sku is unique within one retailer, not globally. Define product_id as a deterministic, URL-safe encoding of (retailer_id, sku). That gives three wins at once: two retailers can both sell "SKU-100" without colliding, every GET /products/{product_id} request tells us which retailer shard to query without an extra lookup table, and a product that is deleted and later re-uploaded gets the exact same product_id.
    • Upload cadence and skew: baseline retailers upload roughly once a week (Part 4 increases new retailers to daily). With a 50-SKU median alongside a 20,000-SKU mean, catalog sizes follow an extreme power law where a tiny fraction of giant retailers hold most of the catalog; assume the largest retailer has 10 million products (~10 GB file).
    • Deleted products and overrides: when a retailer omits a product from a snapshot, we mark its base row deleted—called a tombstone (a retained marker row with deleted = true rather than a physical DELETE)—and keep any admin overrides untouched. While tombstoned, the product disappears from reads; if the retailer re-adds that SKU later (for example, when Snapshot 2 fixes a bad Snapshot 1 in Part 3), its admin overrides automatically apply again. Tombstones and overrides untouched for > 180 days are archived.
    • Latency and pagination: 400 ms is our p99 server-side latency target. Returning 10M SKUs in one response (~300 MB) would blow through memory and latency budgets, so SKU listing uses cursor pagination (1,000 SKUs per page).

    Four core invariants our design must guarantee with zero special cases:

    1. A retailer snapshot never overwrites an attribute that has an active admin override.
    2. A retailer deleting a product hides that product from users even if it has admin overrides.
    3. Deleting an admin override immediately exposes the retailer's most recent value for that attribute.
    4. Once a retailer's latest snapshot finishes applying, the visible catalog equals that snapshot merged with active overrides, even if earlier snapshots failed or were superseded mid-flight.
  2. Back-of-the-envelope capacity estimates

    Metric                     Math and estimate
    -------------------------  --------------------------------------------------------------------
    Total products (Part 1)    50,000 retailers x 20,000 avg = 1,000,000,000 (1B) products
    Size skew                  Median = 50 -> 25,000 retailers have <= 50 rows;
                               a few hundred giants hold most of the 1B rows; max = 10M rows (~10 GB)
    Database size              1B rows x ~1 KB normalized JSON = ~1 TB raw -> ~2 TB with indexes
    Admin overrides            ~0.1% of products overridden, ~2 attrs each -> ~2M small rows
    Read traffic               11,000 QPS total: ~80% product detail (~8.8k QPS), ~20% SKU pages (~2.2k QPS)
    Per-shard read load        Across 16 SQL shards -> ~125 GB data and ~690 reads/s per shard
    Baseline ingestion         Weekly full snapshots: 1B rows / 604,800 s = ~1,650 rows/s compared
                               At ~2% changed products per upload -> ~20M writes/week (~35 writes/s)
    

    Three architectural conclusions follow immediately:

    • 11,000 read QPS is modest for sharded SQL. ~690 indexed reads/s per shard is well within a single PostgreSQL primary's capacity, and 400 ms p99 is generous; Redis caching mainly shields hot viral items and protects tail latency during heavy ingestion.
    • Snapshots are ~98% unchanged data. Rewriting all 20,000 rows on every upload would waste 50x the disk I/O and cache invalidations. Ingestion must stream, hash, diff, and write only actual deltas.
    • Extreme skew (50 rows vs. 10,000,000 rows) is the #1 operational hazard. A single shared FIFO queue would let one 10 GB upload stall thousands of 50-row boutiques.
  3. API design: direct uploads, paginated reads, and admin overrides

    Two API techniques keep uploads scalable and deep SKU listings fast:

    • A pre-signed multipart upload URL is a time-limited, cryptographically signed URL that lets the retailer upload a 10 GB file straight to object storage (such as S3) in parallel chunks without routing gigabytes of file bytes through our API servers.
    • Keyset pagination (after=<last_sku>) fetches the next page with WHERE sku > $after ORDER BY sku LIMIT 1000, using a fast B-tree seek instead of OFFSET 5000000, which would scan and discard 5 million index entries.
    Retailer Ingestion API
    POST   /v1/retailers/{rid}/snapshots
           Body: { "bytes": 10737418240, "sha256": "...", "format": "jsonl" }
           201:  { "seq": 42, "upload_urls": ["..."], "expires_in": 3600 }
    
    POST   /v1/retailers/{rid}/snapshots/42:complete
           202:  { "seq": 42, "status": "RECEIVED" }
    
    GET    /v1/retailers/{rid}/snapshots/42
           200:  { "status": "APPLIED", "rows_read": 500, "added": 4, "changed": 8, "removed": 1 }
    
    User Browsing API
    GET    /v1/retailers/{rid}/skus?limit=1000&after=SKU-0999
           200:  { "skus": ["SKU-1000", ...], "next_after": "SKU-1999" }
    
    GET    /v1/products/{product_id}
           200:  { "product_id": "...", "retailer_id": 7, "sku": "SKU-1000", "attrs": { ... } }
    
    Admin Override API
    PUT    /v1/products/{product_id}/overrides/{attr}   Body: { "value": "Cotton", "reason": "Fix typo" }
    DELETE /v1/products/{product_id}/overrides/{attr}
    GET    /v1/overrides?stale=true&retailer_id=7       # review queue for follow-up #3
    

    Crucially, seq (42) is assigned monotonically when the retailer starts (POST /snapshots) an upload, capturing the retailer's chronological intent regardless of network upload speed or worker scheduling.

  4. Part 1A: Two-layer data model for conflict-free overrides

    Separating authorship cleanly handles updates, product removals, and override deletions in one unified model. If retailer snapshots and admins both edited a single products row, either snapshots would overwrite admin fixes, or ingestion would skip overridden columns and lose the retailer's newest value. Instead, we store two separate layers written by two separate writers and merge them at read time:

    1. retailer_products (written only by snapshot workers): always stores the retailer's latest normalized attributes, even for attributes currently overridden by an admin.
    2. overrides (written only by admins): stores per-attribute (retailer_id, sku, attr) -> value patches.

    We also add a covering index—an index that includes extra non-key columns via INCLUDE (...) so queries read everything they need straight from the index pages without random heap lookups—to make Part 2's bucket diff scan fast.

    CREATE TABLE retailers (
      retailer_id          BIGINT PRIMARY KEY,
      next_seq             BIGINT NOT NULL DEFAULT 1,      -- next seq assigned on POST /snapshots
      latest_complete_seq  BIGINT NOT NULL DEFAULT 0,      -- highest seq whose upload completed
      applied_seq          BIGINT NOT NULL DEFAULT 0,      -- highest seq fully applied & verified
      applied_file_sha256  TEXT,
      has_partial_writes   BOOLEAN NOT NULL DEFAULT false, -- true while an apply is mid-flight
      size_class           TEXT NOT NULL DEFAULT 'small'   -- 'small' | 'medium' | 'large'
    );
    
    CREATE TABLE snapshots (
      retailer_id  BIGINT NOT NULL,
      seq          BIGINT NOT NULL,
      file_uri     TEXT NOT NULL,
      file_sha256  TEXT NOT NULL,
      bytes        BIGINT NOT NULL,
      status       TEXT NOT NULL,  -- UPLOADING|RECEIVED|APPLYING|APPLIED|SUPERSEDED|QUARANTINED|FAILED
      rows_read    BIGINT, rows_added BIGINT, rows_changed BIGINT, rows_removed BIGINT,
      fingerprint  TEXT,
      created_at   TIMESTAMPTZ NOT NULL,
      applied_at   TIMESTAMPTZ,
      PRIMARY KEY (retailer_id, seq)
    );
    
    CREATE TABLE retailer_products (
      retailer_id   BIGINT NOT NULL,
      sku           TEXT NOT NULL,
      attrs         JSONB NOT NULL,               -- retailer's newest normalized attributes
      content_hash  BYTEA NOT NULL,               -- 128-bit hash of canonical normalized attrs
      bucket        SMALLINT NOT NULL,            -- hash(sku) % 256 for bounded-memory parallel diff
      deleted       BOOLEAN NOT NULL DEFAULT false,
      source_seq    BIGINT NOT NULL,
      updated_at    TIMESTAMPTZ NOT NULL,
      PRIMARY KEY (retailer_id, sku)
    );
    CREATE INDEX live_skus_idx ON retailer_products (retailer_id, sku) WHERE NOT deleted;
    CREATE INDEX diff_scan_idx ON retailer_products (retailer_id, bucket)
      INCLUDE (sku, content_hash, deleted);
    
    CREATE TABLE overrides (
      retailer_id      BIGINT NOT NULL,
      sku              TEXT NOT NULL,
      attr             TEXT NOT NULL,
      value            JSONB NOT NULL,
      base_hash_at_set BYTEA,                     -- hash of retailer's attr value when override was set
      stale            BOOLEAN NOT NULL DEFAULT false,
      created_by       TEXT NOT NULL,
      reason           TEXT,
      created_at       TIMESTAMPTZ NOT NULL,
      PRIMARY KEY (retailer_id, sku, attr)
    );
    
    CREATE TABLE override_audit (                 -- immutable append-only audit log
      audit_id        BIGSERIAL PRIMARY KEY,
      retailer_id     BIGINT NOT NULL,
      sku             TEXT NOT NULL,
      attr            TEXT NOT NULL,
      action          TEXT NOT NULL,              -- 'SET' | 'DELETE'
      old_value       JSONB,
      new_value       JSONB,
      retailer_value  JSONB,
      actor           TEXT NOT NULL,
      reason          TEXT,
      at              TIMESTAMPTZ NOT NULL
    );
    

    One 7-line read-merge function satisfies every override requirement automatically:

    def merge_effective_product(base_row, admin_overrides):
        """Combine retailer base_row with admin_overrides dict {attr: value}."""
        if base_row is None or base_row["deleted"]:
            # Retailer deletion wins even when admin overrides exist.
            return None
        effective_attrs = dict(base_row["attrs"])
        for attr_name, override_value in admin_overrides.items():
            # Active admin override masks the retailer's value for that attribute.
            effective_attrs[attr_name] = override_value
        return effective_attrs
    
    Event                                  retailer_products        overrides       What shoppers see
    -------------------------------------  -----------------------  --------------  -------------------------------
    Retailer updates P (attr 'color' has   attrs & hash updated     untouched       Admin's 'color' + retailer's
      an admin override)                     with newest values                       newest price/title
    Retailer deletes P                     deleted = true           untouched       404 Not Found; omitted from SKUs
    Admin deletes override on 'color'      untouched                row deleted     Retailer's newest 'color' right
                                                                    + audit logged    away (already in base_row!)
    Retailer re-adds P in later snapshot   deleted = false, attrs   untouched       P reappears with its overrides
    
  5. Part 1B: Database choice, caching, and the read path

    Database choice: PostgreSQL sharded by retailer_id via a cached directory map (retailer_id -> shard_id).

    • 100% single-shard queries: SKU listings pass retailer_id, and product_id decodes to (retailer_id, sku). A retailer's retailers row, snapshots, retailer_products, and overrides all colocate on the same shard, enabling single-shard ACID transactions for Part 3's snapshot fencing.
    • Manageable shard size: ~2 TB across 16 shards is ~125 GB per shard (each paired with a synchronous standby replica). Giant 10M-SKU retailers (~10 GB) can be placed on dedicated shards via the directory table without rehashing everyone else.

    Read SQL and Redis caching:

    -- 1. Product detail: two fast primary-key lookups on the same shard
    SELECT attrs, deleted FROM retailer_products WHERE retailer_id = $1 AND sku = $2;
    SELECT attr, value    FROM overrides         WHERE retailer_id = $1 AND sku = $2;
    
    -- 2. Paginated SKU listing: index-only range scan on partial index live_skus_idx
    SELECT sku FROM retailer_products
    WHERE retailer_id = $1 AND NOT deleted AND sku > $2
    ORDER BY sku
    LIMIT 1000;
    

    A Redis cache stores the merged product JSON keyed by product_id (10-minute TTL) and page 1 of each retailer's SKU list. Whenever an ingestion batch or an admin override commits, the worker deletes the affected Redis keys (DEL product:{id}). Cache misses read from the shard primary (easily handled at < 700 QPS/shard total) so replication lag never refills Redis with stale pre-invalidation data.

  6. High-level architecture and end-to-end ingestion flow

     Retailer                                       Shoppers (11k QPS)       Platform Admins
        | 1. POST /snapshots -> seq, S3 URLs                |                       |
        | 2. Multipart upload -----> [ Object Storage ]     v                       v
        | 3. POST :complete                 |        +-------------+         +-------------+
        v                                   |        |  Read API   |         |  Admin API  |
    +--------------+                        |        +---+-----+---+         +------+------+
    | Snapshot API |                        |     hit    |     | miss               |
    +------+-------+                        |   +--------+     |                    | write override
           | 4. Set RECEIVED & bump         |   | Redis  |<----+                    | + audit, then
           |    latest_complete_seq         |   +--------+     |                    | DEL Redis key
           | 5. Enqueue (rid, seq)          v       ^          |                    |
    +--------------+   6. Lease     +---------------+---+      v                    v
    | Size Queues  |--------------->| Ingestion Workers |---> [ Sharded PostgreSQL (16 shards) ]
    | small / med  |                | stream, normalize,| 7.    retailers, snapshots,
    | / large      |                | bucket-diff, batch|       retailer_products, overrides
    +--------------+                +-------------------+
    

    End-to-end flow of an upload:

    1. POST /snapshots atomically increments retailers.next_seq and returns seq plus pre-signed upload URLs.
    2. Retailer streams the file directly to object storage and calls :complete.
    3. In one transaction, Snapshot API marks the snapshot RECEIVED and updates latest_complete_seq = GREATEST(latest_complete_seq, seq). (If seq < latest_complete_seq, a newer upload already completed, so this one is immediately marked SUPERSEDED.)
    4. (retailer_id, seq) is pushed to the retailer's small, medium, or large job queue.
    5. An ingestion worker acquires a per-retailer lease, verifies seq == latest_complete_seq, verifies the file's SHA-256 checksum, sets has_partial_writes = true, and streams rows into 256 hash buckets.
    6. For each bucket 0..255, the worker diffs the file's normalized hashes against the shard's diff_scan_idx and writes only added, changed, and removed rows in fenced transactions of 500 rows, invalidating changed Redis keys after each batch commits.
    7. Once all 256 buckets succeed and pass the Part 5 fingerprint check, the worker sets applied_seq = seq, applied_file_sha256 = sha256, has_partial_writes = false, and marks the snapshot APPLIED.
  7. Part 2: Diffing two snapshots accurately at 10M-row scale

    Compare against stored retailer_products, not the previous snapshot file. Suppose Snapshot 1 crashed or was superseded halfway through after updating 25,000 rows in the database. If Snapshot 2 diffed against Snapshot 1's file, it could see a row where Snapshot 2 disagrees with the database or skip fixing rows left behind by the half-applied run. Diffing against retailer_products always computes the exact delta needed to make the database match the new file.

    Safe manifest fast-path: When a snapshot reaches APPLIED, the worker saves a compact sorted (sku, content_hash) manifest file to object storage and sets has_partial_writes = false. If the next snapshot starts while has_partial_writes is still false, retailer_products is guaranteed identical to that manifest, so the worker can diff against the manifest in object storage with zero database reads. Whenever has_partial_writes is true (an intervening apply failed or was superseded), the worker falls back to scanning diff_scan_idx.

    Per-row 128-bit hash + 256 hash buckets keep memory tiny:

    Each row is canonically normalized and hashed into a 16-byte content_hash (collision probability ~2^-128). Partitioning SKUs by bucket = hash(sku) % 256 bounds peak worker RAM to a single bucket (~40,000 rows = ~4 MB even for a 10M-row giant!) while running in O(n + m) linear time:

    def diff_bucket(file_hashes, db_rows):
        """Compare one bucket of a snapshot against stored base rows.
    
        file_hashes: dict[sku, bytes] from the incoming snapshot file.
        db_rows:     dict[sku, tuple[bytes, bool]] -> (content_hash, deleted) from DB.
        """
        added_skus = []
        changed_skus = []
        removed_skus = []
    
        for sku, new_hash in file_hashes.items():
            existing = db_rows.get(sku)
            if existing is None or existing[1]:
                # Either never seen before, or currently a deleted tombstone coming back.
                added_skus.append(sku)
            elif existing[0] != new_hash:
                changed_skus.append(sku)
            # Else hashes match and row is live -> unchanged (skip write!).
    
        for sku, (_, is_deleted) in db_rows.items():
            if not is_deleted and sku not in file_hashes:
                removed_skus.append(sku)
    
        return added_skus, changed_skus, removed_skus
    

    Cost for the largest 10M-row (~10 GB) retailer: streaming & normalizing 10 GB across 16 worker cores at ~8 MB/s/core takes ~80 seconds; scanning diff_scan_idx (10M x ~50 B = ~500 MB index-only) takes seconds; writing a 2% delta (200,000 rows = 400 batches of 500) finishes in well under two minutes.

    Canonical normalization prevents phantom diffs: before hashing, parse attributes against a typed schema—serialize JSON with sorted keys, normalize text to Unicode NFC with trimmed whitespace and \n newlines, convert prices to integer minor units ("10.0" and "10.00" both become 1000 cents), normalize booleans/enums ("TRUE" -> true), sort unordered sets (tags) while preserving ordered arrays (image_urls), treat null/empty/missing identically, and strip volatile export metadata (exported_at). Also reject files with duplicate SKUs or > 1% corrupt lines, and hold any file missing > 30% of applied_seq's SKUs in QUARANTINED so a truncated export never wipes out a retailer's catalog.

  8. Part 3: Ensuring a corrective upload supersedes a mistaken snapshot

    Concurrent workers touching the same retailer must never allow an earlier upload to overwrite a newer one. Suppose a retailer starts Snapshot 1 (seq = 1, wrong) and moments later uploads Snapshot 2 (seq = 2, fixed). We guarantee the catalog ends up matching Snapshot 2 regardless of timing using creation-order sequencing + database row fencing.

    A fencing check verifies inside every database write transaction that the writer's sequence token has not been superseded, protecting the database even if an old worker freezes during a garbage-collection pause and outlives its distributed lease:

    -- Executed for every 500-row apply batch by worker running (rid, my_seq):
    BEGIN;
    SELECT latest_complete_seq FROM retailers WHERE retailer_id = $rid FOR SHARE;
    -- Application check: if latest_complete_seq != $my_seq, ROLLBACK and mark snapshot SUPERSEDED!
    
    INSERT INTO retailer_products (retailer_id, sku, attrs, content_hash, bucket, deleted, source_seq, updated_at)
    VALUES ... -- up to 500 added, changed, or newly tombstoned rows
    ON CONFLICT (retailer_id, sku) DO UPDATE
    SET attrs = EXCLUDED.attrs,
        content_hash = EXCLUDED.content_hash,
        deleted = EXCLUDED.deleted,
        source_seq = EXCLUDED.source_seq,
        updated_at = EXCLUDED.updated_at;
    COMMIT;
    

    When Snapshot 2 finishes uploading, :complete runs UPDATE retailers SET latest_complete_seq = GREATEST(latest_complete_seq, 2) WHERE retailer_id = $rid. Because UPDATE acquires an exclusive row lock that conflicts with FOR SHARE, it waits a few milliseconds for any in-flight batch of Snapshot 1 to finish, commits latest_complete_seq = 2, and guarantees zero further batches of Snapshot 1 can ever commit.

    When Snapshot 2 completes...   What happens to Snapshot 1           What Snapshot 2 diffs against
    -----------------------------  -----------------------------------  --------------------------------------
    Before Snapshot 1 starts       Sees 1 < 2 immediately -> SUPERSEDED Clean database state from Snapshot 0
                                   (even if upload 1 finishes later!)
    While Snapshot 1 is applying   Next batch fails FOR SHARE fence ->  Snapshot 0 + Snapshot 1's committed
                                   aborts; has_partial_writes is true   batches (scans DB, not manifest!)
    After Snapshot 1 finished      Already APPLIED                      Snapshot 1's complete state / manifest
    

    Why the stored catalog converges cleanly to Snapshot 2: Snapshot 2 diffs every bucket against what is currently stored after Snapshot 1 has permanently stopped writing:

    • Wrongly modified products have db_hash != snap2_hash -> overwritten with Snapshot 2's attributes.
    • Wrongly deleted products sit as deleted = true tombstones -> diff_bucket classifies them as added, flipping deleted = false while their untouched rows in overrides immediately take effect again.
    • Wrongly added products exist in retailer_products (deleted = false) but not in Snapshot 2 -> diff_bucket classifies them as removed, setting deleted = true.
  9. Part 4: Scaling to 50,000 new daily retailers with extreme skew

    Separate scanned/diffed rows from mutated database rows when 50,000 additional merchants upload daily (still 20k mean, 50 median):

    Metric                      Math and capacity plan
    --------------------------  -----------------------------------------------------------------------
    Daily rows read/compared    New: 50k x 20k = 1.0B/day; Existing weekly: 1.0B / 7 = ~0.14B/day
                                Total = ~1.14B rows/day (~13.2k rows/s avg; ~40k rows/s in 4h night peak)
    Compute for parse+hash      ~1.14 TB/day (~40 MB/s peak). Realistic JSON schema validation + Unicode
                                normalization + hashing runs at ~5-10 MB/s per vCPU -> ~4-8 active cores
                                at peak; provision an autoscaled pool of 32-64 vCPUs for bursts/retries
    Steady-state DB writes      ~2% daily change -> ~23M writes/day (~265/s avg, ~800/s peak across fleet)
    One-time onboarding burst   50k newcomers' first uploads insert 1B rows once; paced at 50k inserts/s
                                across shards, onboarding completes in ~5.5 hours without hurting reads
    Database & S3 storage       2B total products -> ~4 TB indexed across 32 SQL shards (~125 GB/shard);
                                7-day raw snapshot retention in object storage -> ~8 TB
    

    Making near-unchanged daily uploads almost free:

    1. Exact file-hash short-circuit: if NOT has_partial_writes and the new snapshot's file_sha256 == applied_file_sha256, verify the stream's SHA-256 and mark APPLIED with zero row parsing and zero DB queries.
    2. Object-storage manifest diff: otherwise, when NOT has_partial_writes, diff against applied_seq's saved (sku, content_hash) manifest so unchanged rows never even touch PostgreSQL.

    Fairness and isolation across 200,000x retailer skew:

    • Size-tiered queues and worker pools: route retailers into small (< 10k SKUs), medium (< 1M SKUs), and large (>= 1M SKUs) queues based on previous row count or uploaded byte size. The 50% of retailers with <= 50 products finish in ~1 second in the small lane, completely insulated from 10M-row giants.
    • Per-retailer coalescing and bucket caps: keep at most one active job per retailer (newer uploads automatically supersede queued older ones) and cap one large job at 16 concurrent bucket workers so one giant cannot monopolize the large pool.
    • Per-shard write rate limiting: enforce a token bucket—a rate limiter that refills write permits at a steady rate, such as 2,000 row writes/s per shard—so heavy onboarding or large diffs never starve sub-400 ms user read queries.
  10. Part 5: Observability and proving catalog correctness

    Passing infrastructure health checks does not prove data accuracy: low CPU and HTTP 200 responses cannot confirm that visible prices match the latest snapshot. Measure both SLOs (service-level objectives: agreed quantitative targets for latency, availability, and freshness) and data integrity:

    • Read & Freshness SLOs: Read API p99 < 400 ms (internal warning alert at 150 ms) and 99.9% non-5xx availability; Ingestion Freshness SLO of <= 10 minutes for 99% of small snapshots and <= 3 hours for 99% of large snapshots, tracked via queue age and per-stage timers (download, normalize, diff, apply).
    • Order-independent post-apply fingerprint: while parsing the file, accumulate (live_row_count, sum(hash64(sku, content_hash)) mod 2^64). Before marking APPLIED, verify this tuple matches the shard's live rows for that retailer (maintained incrementally or scanned across buckets). Any mismatch pages on-call immediately and triggers an idempotent re-diff.
    • Public-API end-to-end sampling & synthetic canary: after each apply, sample 100 random SKUs through GET /v1/products/{id} and assert response == merge(file_row, overrides), catching bugs in merge_effective_product, Redis serialization, or missed cache invalidations. Run a synthetic canary retailer every 15 minutes with known edits, deletions, and overrides.
    • Immutable override audit & distributed tracing: tag every log and trace span with (retailer_id, seq) or request_id, and write every admin change into override_audit inside the same SQL transaction using a DB role that lacks UPDATE/DELETE privileges on override_audit, streaming copies to write-once object storage.
  11. Failure handling and trade-off summary

    Failure scenario                     Impact & automatic recovery
    -----------------------------------  ---------------------------------------------------------------
    Worker crashes mid-apply             Lease expires (30s heartbeat); new worker sees has_partial_writes
                                         = true, diffs against DB rows, and applies only remaining changes
    Queue delivers duplicate job         Lease blocks second worker; even if lease lags, identical fenced
                                         upserts on (retailer_id, sku) are 100% idempotent
    Queue drops a message                Background sweeper re-enqueues RECEIVED snapshots older than 10m
    Truncated / corrupt retailer file    SHA-256 mismatch, >1% parse errors, or >30% SKU drop quarantines
                                         the snapshot before any rows are tombstoned
    Shard primary crash                  Promote synchronous standby; workers retry aborted 500-row batch;
                                         Redis continues serving cached hot products during failover
    

    Core trade-offs summarized:

    • Two tables merged on read vs. single materialized table: adds a cheap same-shard PK lookup on cache misses, but eliminates every race and clobbering bug between retailer uploads and admin overrides.
    • Diffing against DB state vs. previous file: costs an index-only scan when has_partial_writes is true, but makes crash recovery and Part 3 superseding completely self-healing.
    • Database FOR SHARE fencing vs. trusting worker leases alone: requires colocating each retailer on one shard, but guarantees an old stalled worker can never overwrite newer snapshot data.
    • Batch partial visibility vs. all-or-nothing snapshot switching: keeps transactions tiny (~500 rows) and avoids multi-version storage overhead, matching the prompt's relaxed visibility requirement.

Intuition & how it works

Picture the catalog as two transparent sheets stacked in an overhead projector: a bottom sheet (retailer_products) where snapshot ingestion writes the retailer's normalized catalog, and a top overlay sheet (overrides) where platform admins stick per-attribute correction notes. When a shopper views a product, the read API looks down through both sheets at once: any admin note on the top sheet masks that specific attribute underneath, peeling off an admin note instantly reveals whatever newest value the retailer wrote on the bottom sheet, and marking a product deleted on the bottom sheet removes the whole product from view even if sticky notes still sit on the overlay.

A naive design stores one products row per SKU and overwrites every row whenever a retailer uploads a snapshot file. That fails on both correctness and scale: either snapshots wipe out admin overrides, or ingestion skips overridden fields so deleting an override later exposes a stale months-old price; rewriting 100% of a 10-million-SKU file when only 2% of products changed wastes 50x the database writes; and putting all 50,000 retailers into one first-in-first-out queue lets a single 10 GB upload stall thousands of 50-product shops for hours.

Trace four events on SKU "SHOE-1" from Retailer 7 to see how the two-layer model and snapshot sequencing work together:

  1. Snapshot 1 (seq = 1) applies: writes retailer_products(7, "SHOE-1", attrs={"title": "Runner", "price": 9000}, deleted=false). No overrides exist, so shoppers see $90.00.
  2. Admin overrides price to 8500: writes overrides(7, "SHOE-1", "price", 8500) and deletes "SHOE-1" from Redis. Shoppers now see $85.00.
  3. Snapshot 2 (seq = 2) updates price to 9500 and title to "Pro Runner": ingestion hashes the normalized row, detects a hash change, and updates retailer_products to {"title": "Pro Runner", "price": 9500} without touching overrides. Shoppers see "Pro Runner" at the admin's $85.00.
  4. Admin deletes the price override: deletes the row in overrides and invalidates Redis. The very next read merges retailer_products with {} and immediately serves the retailer's newest $95.00 price.

Key trade-offs

  • Read-time two-layer merge vs. write-time materialized product row. Keeping retailer_products and overrides separate guarantees that retailer snapshots and admin edits never overwrite each other and makes override deletion instant. Materializing a single merged table saves one primary-key lookup on cache misses, but forces every ingestion batch and admin action to coordinate writes to the same row—where race conditions and lost-update bugs live.
  • Sharded PostgreSQL vs. wide-column NoSQL (Cassandra / DynamoDB). Sharding PostgreSQL by retailer_id keeps all rows of a retailer on one shard, giving ACID batch transactions for fencing (checking inside the transaction via SELECT ... FOR SHARE that no newer snapshot has completed) plus covering indexes (indexes storing sku, content_hash, and deleted together for fast bucket scans). Wide-column stores automate partition rebalancing, but require per-item conditional writes instead of clean multi-row fenced transactions; at ~2–4 TB and 11,000 QPS, sharded SQL is simpler and more expressive.
  • Diffing against stored DB rows vs. diffing against the previous file. Comparing a new snapshot against retailer_products heals any half-applied state left by a crashed or superseded job. Diffing against a saved object-storage manifest avoids database reads completely, so we use the manifest fast-path only when has_partial_writes = false proves the previous snapshot finished cleanly.
  • Creation-order seq vs. upload-completion order vs. client timestamps. Assigning seq on POST /snapshots captures the order the retailer initiated uploads on our server, whereas ordering by upload completion lets a slow, earlier upload overwrite a fast correction, and trusting file timestamps breaks under skewed retailer clocks.
  • Soft-delete tombstones vs. hard DELETE rows. Marking removed products with a tombstone (deleted = true) while retaining overrides allows corrected snapshots (Part 3) and temporarily out-of-stock SKUs to reappear with their admin fixes intact, trading modest storage overhead and a 180-day archival job for lossless recovery.
  • Size-tiered worker pools (small / medium / large) vs. one shared queue. Isolating queues by retailer catalog size ensures the median 50-SKU retailer finishes in seconds even while 10M-SKU giants run, trading slight pool underutilization for strict tail-freshness fairness.

Common mistakes

  • Storing overrides in the same column as retailer attributes, or skipping overridden attributes during ingestion, which either wipes out admin overrides on the next upload or fails to show the retailer's newest value when an override is deleted.
  • Physically deleting admin overrides when a retailer snapshot omits a product, so a mistaken Snapshot 1 that drops products permanently destroys years of manual admin fixes even after Snapshot 2 restores the products.
  • Diffing Snapshot N against Snapshot N - 1's file unconditionally, leaving behind corrupt or half-applied rows whenever Snapshot N - 1 crashed or was superseded partway through.
  • Hashing raw JSON strings or CSV lines without canonical normalization, causing harmless formatting differences ("10.0" vs "10.00", reordered JSON keys, export timestamps) to look like 10 million changed rows.
  • Relying solely on a distributed worker lease for Part 3 ordering, forgetting that a paused worker can outlive its lease and overwrite Snapshot 2 unless every batch transaction checks latest_complete_seq in the database.
  • Using OFFSET pagination instead of keyset pagination (WHERE sku > $after) for GET /skus, turning deep pages on a 10M-product retailer into multi-second index scans.
  • Monitoring only server health (CPU, 5xx rate, queue length) without post-apply catalog fingerprints or end-to-end read sampling to detect silent data corruption.

Follow-up questions

  • How would you redesign storage and caching so shoppers never observe a partially applied snapshot, and what trade-offs would that introduce? Add multi-version concurrency control at the catalog level: change the base primary key to (retailer_id, sku, seq), have ingestion write new row versions (including tombstones) under its seq, and add visible_seq to retailers. Reads query the newest version per SKU with seq <= visible_seq (after cleaning up any rows from superseded sequences before advancing visible_seq), and flipping visible_seq = new_seq in a single-row update exposes the entire snapshot atomically—paired with embedding visible_seq inside Redis cache keys (product:{rid}:{visible_seq}:{sku}) so caches switch at the exact same instant. This costs extra disk space for multi-version rows until background garbage collection prunes older versions, more write amplification, and slower DISTINCT ON (sku) index scans on uncached SKU listings (though small retailers can still get atomic visibility cheaply by applying their <= 50 rows inside a single SQL transaction).
  • What techniques would you use if one mega-merchant's snapshot required several hours to diff and write? Break latency down by stage (download, normalize, diff, apply) to find the bottleneck: parallelize file download via HTTP byte-range reads and spread parsing/hashing across the 256 SKU buckets on multiple workers (capped at, say, 16 workers so other large retailers aren't starved). Eliminate database diff reads via the object-storage manifest when has_partial_writes is false, checkpoint completed bucket numbers so worker restarts resume from the remaining buckets rather than bucket 0, and move the giant retailer onto a dedicated PostgreSQL shard with a higher token bucket write rate limit (a steady permit-refill cap protecting read latency). If the retailer legitimately mutates millions of prices every hour, partner with them to send incremental change feeds alongside periodic full reconciliation snapshots.
  • How could the platform detect and surface admin overrides whose underlying merchant attribute values changed in later uploads? When an admin sets an override on (retailer_id, sku, attr), record base_hash_at_set—the hash of the retailer's value for attr at that moment—on the overrides row. Whenever a snapshot apply updates changed SKUs, fetch any overrides for those SKUs on the same shard and set stale = (hash(new_retailer_attr) != base_hash_at_set), automatically clearing stale = false if a corrected snapshot restores the original value (as in Part 3) or flagging redundancy if new_retailer_attr == override.value. Surface stale = true rows in a prioritized admin review queue (GET /v1/overrides?stale=true) showing the original retailer value, current retailer value, and active override side by side so admins can re-confirm (updating base_hash_at_set), edit, or delete each override with a full audit entry.

Follow-up questions

Similar questions

More Attentive interview questions

All 16 Attentive questions →