Marketplace Product Reactions and Like Counters

Medium · System Design · Software Engineer · Onsite

Prompt

Architect the backend service powering product reactions on a two-sided wholesale marketplace where independent brands publish merchandise catalogs and retail shops source inventory. Your design must deliver four core capabilities:

  1. Retail buyers can record a like or a dislike on any catalog item.
  2. Retail buyers can browse the collection of items they have previously liked.
  3. Marketplace search result pages display reaction information alongside every returned product card.
  4. Brand sellers can inspect reaction activity across their own listed products.

Key product and scale details are intentionally underspecified—state clear assumptions or resolve ambiguities explicitly:

  • Reaction semantics: Settle whether "dislike" simply clears a prior like or represents a distinct negative state, and ensure a buyer cannot hold conflicting states on the same item.
  • Scale, freshness, and visibility: Define catalog size, read/write traffic rates, whether search cards show both aggregate counts and the viewer's personal state, whether brands view aggregate totals or individual buyer identities, liked-list ordering and pagination depth, and how deactivated items or closed accounts affect stored reactions.

Scope & Expectations

  • Unambiguous state model and idempotent APIs: Define clean state transitions, prevent duplicate counting under client retries or concurrent taps, and expose scalable pagination and batch-enrichment endpoints.
  • Bidirectional access and counter maintenance: Serve both buyer-centric ("items I liked") and product-centric ("likes on this product") reads efficiently while keeping per-product counters accurate without hot-row lock contention.
  • Fast search-page enrichment: Hydrate dozens of search result cards in a single request within tight tail-latency budgets while preserving read-your-writes consistency on the buyer's own reaction indicator.
  • Horizontal scaling and resilience: Handle viral traffic bursts on popular listings, evolve partitioning as storage grows, and degrade gracefully if caches or asynchronous workers lag.

Step-by-step walkthrough

  1. Clarify requirements and settle what "dislike" means

    Before touching databases, we must resolve the biggest product ambiguity in the prompt: does "dislike" simply undo a previous like, or is it a separate negative signal? That single choice changes both our row schema and our counters.

    Agreed behavior (confirm with the interviewer first): Each (retailer_id, product_id) pair acts as a tiny state machine with exactly one current state—LIKE, DISLIKE, or NONE. Setting DISLIKE records a private negative preference (used to hide or demote that item in the retailer's own recommendations, and shown to the owning brand only as an aggregate count) and automatically replaces any prior LIKE so one retailer can never hold both a like and a dislike on the same product. Clearing a reaction returns the pair to NONE. (If the interviewer specifies that "dislike" only means "remove my like," we simply drop the DISLIKE state and dislike_count column; every architectural piece below stays identical.)

    Functional requirements

    1. A retailer sets or clears their reaction on a product (LIKE, DISLIKE, or NONE).
    2. A retailer browses their own liked products sorted newest-liked first, with pagination across thousands of items.
    3. Every search results page (~48 products) displays each product's total like count and whether the searching retailer currently likes it.
    4. A brand views like and dislike counts across its catalog, plus the list of retailers who liked a specific product.

    Non-functional and lifecycle requirements

    • Read-your-writes on personal state: Public like counts may lag by 1–3 seconds (eventual consistency), but if a retailer clicks the heart icon and refreshes search 100 ms later, their own heart icon must stay filled (read-your-writes consistency).
    • Sub-10 ms search enrichment: Fetching like data for 48 products must never run COUNT(*) over raw rows on the fly, and if the likes subsystem is degraded, search must still render products without counts.
    • Idempotent writes: An idempotent operation produces the exact same stored state and count whether a request arrives once or retries three times after a mobile network blip.
    • Product and account lifecycle: Soft-deleting a product hides it from search and liked lists while preserving historical reactions for brand analytics. Closing a retailer account transitions their active reactions to NONE through the normal write path (decrementing product counts cleanly) before deleting the rows.
  2. Back-of-the-envelope numbers

    Let's state realistic wholesale-marketplace assumptions and check whether our bottleneck is write volume, storage size, or read fan-out.

    1. Marketplace entities
       Retailers: 1,000,000 total (200,000 daily active users, or DAU)
       Brands:      100,000 total
       Products: 10,000,000 active catalog items
    
    2. Reaction write traffic
       200,000 DAU x 10 reaction changes/day = 2,000,000 writes/day
       Average: 2,000,000 / 86,400 s = ~23 writes/s
       Peak (5x): ~120 writes/s
    
    3. Reaction table storage (PostgreSQL)
       1,000,000 retailers x 300 lifetime reactions = 300,000,000 rows
       Per row: ~72 B heap tuple + ~30 B primary key + ~118 B indexes/page overhead = ~220 B
       Total:   300M x 220 B = ~66 GB (comfortably fits on a single modern database server!)
    
    4. Search and browse read traffic
       Searches:      200,000 DAU x 30 searches/day = 6,000,000 searches/day
                      Average ~70 searches/s, Peak (5x) ~350 searches/s
       Search fan-out at peak (48 products per results page):
         - Product counts read: 350 pages/s x 48 products = 16,800 product counts/s
                                (fetched as 350 batched calls/s, NOT 16,800 separate RPCs!)
         - Own-state checks:    350 batched lookups/s (48 product IDs per lookup)
       Liked-list views: ~200,000/day (~2.3/s avg)    Brand portal views: ~20,000/day
    
    5. Precomputed counter size
       10,000,000 products x ~40 B in PostgreSQL = ~400 MB table
       10,000,000 keys in Redis (~100 B/key with key string + metadata overhead) = ~1 GB RAM
    

    Three clear lessons stand out from these numbers:

    • Total write rate is modest (~120 writes/s at peak). A single PostgreSQL primary handles this effortlessly—sharding on day one would add needless operational complexity.
    • Reads outnumber writes by 140 to 1 (16,800 product counts read/s vs. 120 writes/s). Counts must sit precomputed in a fast cache and be fetched in a single batch per search page.
    • The hardest problems are concurrency and skew, not raw terabytes: serving two opposite query directions cleanly, preventing duplicate counts under retries/crashes, and absorbing sudden bursts when one viral product receives thousands of likes in a minute.
  3. API design: set-state writes, cursor pagination, and batch search reads

    We expose external endpoints for retailers and brands (extracting retailer_id or brand_id from the authenticated token) and one internal batch endpoint for the search service:

    # 1. Set or clear a reaction (idempotent set-state, NEVER toggle!)
    PUT    /v1/products/{product_id}/reaction
           body: {"type": "LIKE" | "DISLIKE"}
           -> 200 {"product_id": "p_405", "type": "LIKE", "updated_at": "2026-09-15T14:20:00Z"}
    
    DELETE /v1/products/{product_id}/reaction
           -> 204 No Content   (sets state to NONE)
    
    # 2. Retailer's liked products list (newest liked first, cursor-paginated)
    GET    /v1/me/likes?limit=50&cursor=<opaque_base64_of_updated_at_and_product_id>
           -> 200 {"items": [{"product_id": "p_405", "liked_at": "...", "summary": {...}}],
                   "next_cursor": "..."}
    
    # 3. Internal batch enrichment called once per search results page
    POST   /internal/v1/reactions:batchGet
           body: {"retailer_id": "r_19", "product_ids": ["p_1", "p_2", "... up to 100"]}
           -> 200 {"items": {"p_1": {"like_count": 940, "my_reaction": "LIKE"},
                             "p_2": {"like_count": 27,  "my_reaction": "NONE"}}}
    
    # 4. Brand portal endpoints (authorized so brand_id matches the authenticated brand)
    GET    /v1/brands/{brand_id}/products/reactions?sort=likes_desc&limit=50&cursor=...
           -> 200 {"items": [{"product_id": "p_1", "like_count": 940, "dislike_count": 18}], ...}
    
    GET    /v1/brands/{brand_id}/products/{product_id}/likers?limit=50&cursor=...
           -> 200 {"items": [{"retailer_id": "r_19", "store_name": "Cedar & Loom", "liked_at": "..."}], ...}
    

    Two API choices eliminate whole classes of bugs:

    • PUT desired state instead of POST /toggle: Look at what happens when a phone loses signal right after the server processes a click and the app retries:
    Toggle API (broken):   Initial: NONE --click--> LIKE --network retry!--> NONE  (accidental un-like!)
    Set-State API (safe):  Initial: NONE --PUT LIKE--> LIKE --network retry!--> LIKE  (idempotent!)
    
    • Cursor (keyset) pagination instead of OFFSET: If a retailer scrolls to page 100 of their liked items, OFFSET 5000 LIMIT 50 forces the database to scan and discard 5,000 index entries first—and shifts items across page boundaries if they like a new product mid-scroll. Passing a cursor ((liked_at, product_id) of the last item on the previous page) jumps directly to the next 50 entries in O(log N) B-tree lookup time.
  4. Data model: one source-of-truth table for two read directions

    Notice the core bidirectional data-modeling tension: "items Retailer R liked" and "retailers who liked Product P" traverse the exact same many-to-many edge from opposite sides. On a single relational database (~66 GB), one authoritative reactions table with targeted indexes serves both directions with zero synchronization lag:

    CREATE TABLE reactions (
      retailer_id  BIGINT      NOT NULL,
      product_id   BIGINT      NOT NULL,
      brand_id     BIGINT      NOT NULL,     -- denormalized from product (immutable) for brand queries
      type         SMALLINT    NOT NULL,     -- 0 = NONE, 1 = LIKE, 2 = DISLIKE
      created_at   TIMESTAMPTZ NOT NULL,
      updated_at   TIMESTAMPTZ NOT NULL,
      PRIMARY KEY (retailer_id, product_id)  -- enforces 1 state per pair + fast search "my_reaction" lookup
    );
    
    -- Direction 1 (Retailer -> Products): "My liked products, newest first"
    -- Partial index (WHERE type = 1) skips DISLIKE and cleared NONE rows completely!
    CREATE INDEX reactions_liked_by_retailer
      ON reactions (retailer_id, updated_at DESC, product_id DESC)
      WHERE type = 1;
    
    -- Direction 2 (Product -> Retailers): "Which retailers liked this product, newest first"
    CREATE INDEX reactions_likers_by_product
      ON reactions (product_id, updated_at DESC, retailer_id DESC)
      WHERE type = 1;
    
    -- Precomputed per-product counters (never COUNT(*) on the read path!)
    CREATE TABLE product_reaction_counts (
      product_id    BIGINT      PRIMARY KEY,
      brand_id      BIGINT      NOT NULL,
      like_count    INT         NOT NULL DEFAULT 0,
      dislike_count INT         NOT NULL DEFAULT 0,
      updated_at    TIMESTAMPTZ NOT NULL
    );
    
    CREATE INDEX counts_by_brand
      ON product_reaction_counts (brand_id, like_count DESC, product_id DESC);
    
    -- Deduplication ledger for at-least-once stream consumers (pruned after 24 hours)
    CREATE TABLE applied_events (
      event_id    TEXT        PRIMARY KEY,   -- unique WAL log sequence number + row key
      applied_at  TIMESTAMPTZ NOT NULL
    );
    

    Why every detail of this schema earns its keep:

    • Composite primary key (retailer_id, product_id): Enforces at most one state per pair at the storage level and answers "Which of these 48 search results did Retailer R like?" via direct primary-key probes.
    • Soft-clearing to type = 0 (NONE) plus partial indexes (WHERE type = 1): Keeping a cleared row as type = 0 gives concurrent requests a stable row to lock and gives change-stream events an explicit before -> after transition (1 -> 0). Adding WHERE type = 1 (partial indexes, which index only rows matching a filter) keeps NONE and DISLIKE rows out of both listing indexes, saving gigabytes of RAM and avoiding index maintenance on un-likes! A background vacuum job purges type = 0 rows untouched for 90+ days.
    • Matching DESC, DESC sort directions in composite indexes: Because pagination orders by ORDER BY updated_at DESC, product_id DESC, indexing (updated_at DESC, product_id ASC) would prevent a pure forward B-tree scan and force an in-memory sort on ties.
  5. High-level architecture

    The reactions row in PostgreSQL is our single source of truth. Every derived view—product counters, the Redis count cache, and warehouse analytics—flows asynchronously from PostgreSQL's committed WAL (write-ahead log, the database's internal append-only journal of committed changes):

      Retailer App / Web                 Brand Portal
              |                               |
              v                               v
       +---------------------------------------------+
       | API Gateway (TLS, Auth -> retailer/brand_id)|
       +------+---------------+---------------+------+
              |               |               |
              v               v               v
      Reactions Service   Search Service    Brand Insights Service
        | 1-row ACID txn    | 1. Search engine -> 48 product_ids     | reads replica:
        | (no counter lock) | 2. Parallel <= 10 ms enrichment:       | - counts_by_brand
        v                   |    a) My state: PK probe on Primary    | - likers_by_product
      PostgreSQL Primary <--+    b) Counts:   Redis MGET (miss->DB)  |
      (reactions table)     |                                        |
        |        \          |                                        |
        |         +-------->|--------> Read Replicas <---------------+
        |                   |          (liked list + brand views)
        | CDC (Debezium logical replication, REPLICA IDENTITY FULL)
        v
      Kafka topic: "reaction-changes" (partitioned by product_id!)
        |                                     \
        v                                      +--> Cloud Warehouse / OLAP
      Counter Service                               (append-only event log for
      (1 consumer per partition;                     historical time-series charts)
       coalesces deltas for 1s)
        |
        v
      product_reaction_counts (PostgreSQL) ---write-through absolute count---> Redis Cache (~1 GB)
    
  6. Deep dive 1: Idempotent writes and race-free concurrent clicks

    The write endpoint touches only the (retailer_id, product_id) row—never the shared product counter—so 10,000 retailers liking a viral product write 10,000 distinct rows with zero lock contention across users. Still, we must guard against two same-user edge cases: network retries / double-clicks and two concurrent requests on a brand-new pair.

    NONE = 0
    LIKE = 1
    DISLIKE = 2
    
    
    def set_reaction(
        db,
        retailer_id: int,
        product_id: int,
        brand_id: int,
        new_type: int,
    ) -> str:
        """Atomically set (retailer_id, product_id) to NONE, LIKE, or DISLIKE."""
        with db.transaction():
            # 1. If clearing (NONE), lock existing row if present; never insert junk NONE rows!
            if new_type == NONE:
                row = db.query_one(
                    "SELECT type FROM reactions "
                    "WHERE retailer_id = %s AND product_id = %s FOR UPDATE",
                    (retailer_id, product_id),
                )
                if row is None or row.type == NONE:
                    return "unchanged"
            else:
                # 2. For LIKE/DISLIKE, ensure a placeholder row exists so FOR UPDATE has a row to lock
                #    even if two first-time clicks from the same user arrive at the exact same ms.
                db.execute(
                    "INSERT INTO reactions "
                    "(retailer_id, product_id, brand_id, type, created_at, updated_at) "
                    "VALUES (%s, %s, %s, 0, now(), now()) "
                    "ON CONFLICT (retailer_id, product_id) DO NOTHING",
                    (retailer_id, product_id, brand_id),
                )
                row = db.query_one(
                    "SELECT type FROM reactions "
                    "WHERE retailer_id = %s AND product_id = %s FOR UPDATE",
                    (retailer_id, product_id),
                )
                if row.type == new_type:
                    # Duplicate retry or double-click: exit without writing WAL or changing updated_at!
                    return "unchanged"
    
            # 3. State actually changed -> update type and bump updated_at for newest-first sorting
            db.execute(
                "UPDATE reactions SET type = %s, updated_at = now() "
                "WHERE retailer_id = %s AND product_id = %s",
                (new_type, retailer_id, product_id),
            )
            return "changed"
    

    Trace why each step is necessary:

    • No junk rows on DELETE: Calling DELETE (new_type = 0) on a product the retailer never reacted to sees row is None and returns "unchanged" immediately without inserting dead rows.
    • Race-free first click: SELECT ... FOR UPDATE cannot lock a row that does not exist yet. Running INSERT ... VALUES (..., 0, ...) ON CONFLICT DO NOTHING first ensures a row exists; if two concurrent requests race on a first reaction, the second waits on the row lock, sees the first winner's state, and applies a clean state transition.
    • Zero-cost duplicate retries: When row.type == new_type, no UPDATE runs, updated_at does not jump forward, and zero CDC events fire.
    • Why we never dual-write to Redis here: Calling db.commit() followed by redis.incr() in application code (dual writing) leaks permanent counter drift whenever a process crashes between the two calls. Streaming committed changes out of PostgreSQL's WAL eliminates dual writes completely.
  7. Deep dive 2: Keeping counters accurate, coalesced, and hot-spot free

    1. Computing exact deltas from before -> after transitions

    We configure CDC (change data capture, streaming row changes from PostgreSQL logical replication via Debezium) with ALTER TABLE reactions REPLICA IDENTITY FULL so every UPDATE event in the WAL carries both before.type and after.type (an alternative is inserting a small reaction_outbox row inside set_reaction). Every possible transition maps cleanly to (like_delta, dislike_delta):

    Transition           like_delta   dislike_delta
    NONE    -> LIKE          +1             0      (new like)
    LIKE    -> NONE          -1             0      (un-like)
    NONE    -> DISLIKE        0            +1      (new dislike)
    DISLIKE -> NONE           0            -1      (clear dislike)
    LIKE    -> DISLIKE       -1            +1      (switched heart to thumbs-down)
    DISLIKE -> LIKE          +1            -1      (switched thumbs-down to heart)
    NONE    -> NONE           0             0      (placeholder insert from Step 2 above)
    
    from typing import Dict, Iterable, Optional, Tuple
    
    NONE = 0
    LIKE = 1
    DISLIKE = 2
    
    
    def compute_count_delta(before_type: Optional[int], after_type: int) -> Tuple[int, int]:
        """Convert one row's state transition into (like_delta, dislike_delta)."""
        like_delta = 0
        dislike_delta = 0
    
        if before_type == LIKE:
            like_delta -= 1
        elif before_type == DISLIKE:
            dislike_delta -= 1
    
        if after_type == LIKE:
            like_delta += 1
        elif after_type == DISLIKE:
            dislike_delta += 1
    
        return like_delta, dislike_delta
    

    2. Coalescing bursts in memory and deduplicating retries

    We partition the "reaction-changes" Kafka topic by product_id (overriding Debezium's default primary-key partitioning). That routes every event for Product P_405—in strict database commit order—to one single consumer instance. That consumer buffers events for 1 second, sums deltas per product in memory (coalescing), and commits one batched database transaction:

    def apply_counter_batch(db, redis_client, events: Iterable) -> None:
        """Deduplicate CDC events, coalesce deltas per product, and write through to Redis."""
        events_list = list(events)
        if not events_list:
            return
    
        updated_like_counts: Dict[int, int] = {}
    
        with db.transaction():
            # 1. Filter out any events already applied before a consumer restart (at-least-once safety)
            event_ids = [e.event_id for e in events_list]
            already_seen = db.fetch_existing_event_ids(event_ids)
    
            # product_id -> (brand_id, net_like_delta, net_dislike_delta)
            coalesced: Dict[int, Tuple[int, int, int]] = {}
    
            for e in events_list:
                if e.event_id in already_seen:
                    continue
                already_seen.add(e.event_id)
                db.insert_applied_event(e.event_id)
    
                d_like, d_dislike = compute_count_delta(e.before_type, e.after_type)
                if d_like == 0 and d_dislike == 0:
                    continue
    
                _, prev_like, prev_dislike = coalesced.get(e.product_id, (e.brand_id, 0, 0))
                coalesced[e.product_id] = (e.brand_id, prev_like + d_like, prev_dislike + d_dislike)
    
            # 2. Upsert one net delta per product and read back the exact new absolute like_count!
            for product_id, (brand_id, like_delta, dislike_delta) in coalesced.items():
                row = db.query_one(
                    "INSERT INTO product_reaction_counts "
                    "(product_id, brand_id, like_count, dislike_count, updated_at) "
                    "VALUES (%s, %s, GREATEST(0, %s), GREATEST(0, %s), now()) "
                    "ON CONFLICT (product_id) DO UPDATE SET "
                    "  like_count    = GREATEST(0, product_reaction_counts.like_count + %s), "
                    "  dislike_count = GREATEST(0, product_reaction_counts.dislike_count + %s), "
                    "  updated_at    = now() "
                    "RETURNING like_count",
                    (product_id, brand_id, like_delta, dislike_delta, like_delta, dislike_delta),
                )
                updated_like_counts[product_id] = row.like_count
    
        # 3. After DB commit: write ABSOLUTE counts to Redis (1h TTL) and commit Kafka offsets
        if updated_like_counts:
            redis_client.mset_with_ttl(updated_like_counts, ttl_seconds=3600)
    

    Notice three critical engineering safeguards here:

    • Upsert prevents silent lost likes on brand-new products: If a shopper likes a newly listed product 100 ms before a catalog worker creates its counter row, INSERT ... ON CONFLICT DO UPDATE creates and increments the row atomically instead of updating 0 rows and dropping the like!
    • Viral products cause 1 SQL write/second: Even if 10,000 retailers like one hit product in 60 seconds, all 10,000 events land on the same partition and collapse into 60 one-row updates (1/s).
    • Crash-proof at-least-once delivery: Because applied_events commits in the same PostgreSQL transaction as product_reaction_counts—and Redis receives the RETURNING absolute like_count (never INCRBY)—a consumer crash at any line can replay the Kafka batch with zero double-counting.
  8. Deep dive 3: Sub-10 ms search enrichment, liked lists, and brand views

    Every search results page must hydrate reaction badges across 48 products at once within a 10 ms latency budget:

    Search Service receives query q from Retailer r_19:
      1. Query Search Index (Elasticsearch / OpenSearch) -> returns 48 product_ids     [~50 ms]
      2. Call reactions:batchGet(retailer_id=r_19, product_ids=[p_1..p_48])            [<= 10 ms]:
           In parallel:
           +-- Path A (Public counts):
           |     Redis MGET rc:p_1 .. rc:p_48                                          [~1 ms]
           |     If any keys missed cache:
           |       SELECT product_id, like_count FROM product_reaction_counts
           |        WHERE product_id = ANY(:missed_ids)
           |       Backfill Redis using SET key val EX 3600 NX  (NX = only if absent!)
           |
           +-- Path B (Retailer r_19's own hearts — read-your-writes!):
                 SELECT product_id, type FROM reactions
                  WHERE retailer_id = :r_19 AND product_id = ANY(:p_1_to_48)           [~2 ms on PK]
      3. Merge counts + own state; if r_19 has my_reaction=LIKE and updated_at > now() - 5s,
         ensure displayed count >= 1 (client also applies optimistic +1 immediately on click).
    

    Why Redis SET ... NX (set only if key does not exist) matters on a cache miss: if a cache miss reads 63 from PostgreSQL, and 1 ms later the counter service writes 64 to Redis, SET NX prevents the slow reader from overwriting 64 back to 63! And why counts stay out of Elasticsearch by default: in Lucene-based search indices, updating a numeric field re-indexes the document segment; keeping counts in Redis avoids 2,000,000 unnecessary document re-indexes per day.

    Keyset SQL queries for the liked list and brand portal (served from read replicas):

    -- Retailer's liked products (uses partial index reactions_liked_by_retailer; O(limit) at any depth!)
    SELECT product_id, updated_at AS liked_at
    FROM reactions
    WHERE retailer_id = :r
      AND type = 1
      AND (updated_at, product_id) < (:cursor_ts, :cursor_product_id)
    ORDER BY updated_at DESC, product_id DESC
    LIMIT 50;
    
    -- Brand's catalog sorted by most liked (uses counts_by_brand)
    SELECT product_id, like_count, dislike_count
    FROM product_reaction_counts
    WHERE brand_id = :b
      AND (like_count, product_id) < (:cursor_likes, :cursor_product_id)
    ORDER BY like_count DESC, product_id DESC
    LIMIT 50;
    
  9. Scaling from 1x to 10x and sharding both directions

    • At 1× scale (300M rows, ~66 GB, ~120 writes/s peak): One PostgreSQL primary with two read replicas, a 2 GB Redis replication group, 6 Kafka partitions, and 3 counter workers easily meet every latency and availability target.
    • At 10× scale (3B rows, ~660 GB, ~1,200 writes/s peak, ~3,500 searches/s): Table maintenance (vacuuming, index rebuilds, backup restore times on ~660 GB) motivates horizontal sharding (splitting rows across multiple independent database primaries):
      • Shard reactions by hash(retailer_id): Both set_reaction, GET /v1/me/likes, and Search Path B (WHERE retailer_id = :r AND product_id = ANY(...)) hit one single shard!
      • Materialize a second projection product_reactions sharded by hash(product_id): Once reactions is sharded by retailer, a brand asking "who liked Product P_405?" would otherwise scatter-gather across every shard. Instead, a Kafka consumer writes LIKE transitions into product_reactions(product_id, updated_at DESC, retailer_id) sharded by product_id, keeping brand liker queries single-shard with ~1 second of acceptable lag.
      • Absorb hot-product read spikes: Add a 2-second in-process LRU cache (Least Recently Used memory cache) inside each reactions-service pod so a homepage product appearing in every search hits Redis only once every 2 seconds per pod.
      • Monitor PostgreSQL replication-slot lag: If a CDC consumer halts, PostgreSQL retains WAL segments on disk; alert well before disk fills.
  10. Failure handling and trade-off summary

    Failure scenario User-visible impact Recovery & mitigation
    PostgreSQL primary crashes Writes fail for ~10–20 s during failover Promote synchronous standby with failover logical replication slots; clients safely retry idempotent PUT; search falls back to replica reads
    Debezium CDC or Counter worker crashes Reactions save normally; public counts freeze briefly Alert on Kafka consumer lag > 15 s; on restart, WAL slot resumes with zero lost events and applied_events skips duplicates
    Redis cache cluster unreachable Slightly higher DB load on counts table Batch-read product_reaction_counts by PK (~350/s is easy for replicas); if slow (> 10 ms), search renders cleanly without like counts
    Likes service exceeds 10 ms search timeout Zero search outage Search circuit-breaker drops the likes badge rather than failing revenue-generating product search
    Logic bug corrupts counters Counts drift from true reaction rows Nightly replica reconciliation job detects discrepancies and funnels single-writer repair commands through Kafka

    Summary of core trade-offs

    Design choice What we gain What we pay
    3-state row (NONE/LIKE/DISLIKE) + PUT set-state API Mathematically idempotent retries; impossible to hold contradictory reactions Requires upfront product agreement on DISLIKE semantics
    Single table + partial indexes (then dual sharded projections at 10×) Strong consistency at 1×; single-shard reads in both directions at 10× Extra storage and ~1 s eventual consistency on brand liker lists once sharded
    Asynchronous CDC + 1-second per-product coalescing Zero hot-row locks on viral products; zero dual-write drift 1–3 s lag on public counts; requires applied_events dedupe table
    Primary PK lookup for searcher's own heart + cached counts Instant read-your-writes on heart icon + 1 ms batch counts Small PK read load (~350 batched queries/s) on primary

Intuition & how it works

Think of a marketplace product-likes backend like an election ballot cabinet paired with a digital stadium scoreboard. Each retailer gets exactly one slot per product inside the cabinet where their current choice sits (LIKE, DISLIKE, or NONE)—that table is our source of truth (the single authoritative record). Instead of making thousands of shoppers stand in single file to manually flip digits on a shared scoreboard whenever a product goes viral—or recounting 50,000 paper slips from scratch every time someone loads a 48-product search page—a background clerk watches the database's committed change log, adds up net changes once per second for each product, and posts the finished totals onto fast lookup boards (precomputed counters in PostgreSQL and Redis).

A naive design breaks in three predictable places. Running SELECT COUNT(*) per product during search scans millions of index entries per second as soon as popular items accumulate thousands of likes. Updating a shared product counter inside the user's click transaction serializes concurrent likes on a hot item behind one database row lock, while updating PostgreSQL and calling INCR in Redis separately in application code (dual writes) permanently corrupts counts whenever a server crashes mid-request. Even exposing POST /toggle causes mobile retries on flaky networks to accidentally un-like what the user just liked.

Concrete 4-step walkthrough (Retailer R_19 double-clicks Like on Brand B_8's Product P_405, currently at 63 likes)

  1. Idempotent click & double-click (14:20:00.100): R_19's app sends PUT /v1/products/P_405/reaction {"type": "LIKE"} twice due to an accidental double-tap. Request 1 locks (R_19, P_405) and updates NONE -> LIKE. Request 2 acquires the lock 5 ms later, sees type == LIKE already, and returns unchanged without emitting a second change event.
  2. Immediate search read-your-writes (14:20:00.250): R_19 returns to search results showing 48 products including P_405. In parallel (< 10 ms), the backend batch-fetches public counts via one Redis MGET (still 63) and probes (R_19, P_1..P_48) by primary key on the PostgreSQL primary (my_reaction = LIKE), while the client renders a filled heart and optimistic 64.
  3. 1-second coalesced counter update (14:20:01.000): CDC (change data capture, streaming committed edits from PostgreSQL's internal write-ahead log) delivers NONE -> LIKE (+1) to the Kafka partition for P_405. The counter consumer deduplicates the event_id, upserts product_reaction_counts (63 -> 64) in one transaction, and writes the new absolute value 64 into Redis.
  4. Brand portal check: Brand B_8 opens its analytics tab, reading P_405: 64 likes from product_reaction_counts and seeing R_19 at the top of P_405's likers list via a read replica.

Key trade-offs

  • Asynchronous CDC counters vs. synchronous in-transaction counters: Updating product_reaction_counts inside set_reaction gives zero-lag exact counts with fewer moving parts, and would survive ~120 average writes/s—but it stalls under row-lock contention on viral products and requires distributed two-shard transactions once reactions is sharded by retailer. Streaming deltas asynchronously via CDC adds 1–3 seconds of count lag and a deduplication table (applied_events), in exchange for lock-free user writes, zero dual-write drift, and clean horizontal sharding.
  • Incremental +1/-1 deltas vs. periodic COUNT(*) recounts: Applying coalesced deltas costs O(1) database work whether a product has 5 likes or 500,000 likes, at the cost of needing at-least-once deduplication (recording processed event IDs so redeliveries never double-count) and a nightly audit job. Recounting changed products via an index scan is naturally self-healing, but degrades precisely on the most-liked viral products.
  • One table with two partial indexes vs. two sharded tables: Below ~500 GB, one PostgreSQL reactions table with two partial indexes (indexes storing only WHERE type = 1 rows, skipping NONE and DISLIKE rows) serves both "my liked products" and "who liked this product" with zero replication code. Once sharded by retailer_id at 10× scale, maintaining a second Kafka-fed product_reactions table sharded by product_id trades extra storage and ~1 s lag to avoid slow scatter-gather queries across all shards.
  • Set-state PUT + soft NONE rows vs. POST /toggle + hard DELETEs: PUT {"type": "LIKE"} makes client retries completely safe, and keeping cleared rows as type = 0 provides a concrete row for SELECT ... FOR UPDATE to lock and a clean before -> after delta in CDC, at the minor cost of periodically vacuuming old type = 0 rows.
  • Keeping like counts out of the search index vs. indexing them: Fetching counts from Redis alongside search results avoids re-indexing search documents 2 million times a day (expensive in Lucene-based engines like Elasticsearch where updates rewrite segments), trading off native ORDER BY like_count inside the search engine unless coarse bucketed updates are added.

Common mistakes

  • Leaving "dislike" ambiguous or storing separate likes and dislikes tables: Two uncoordinated tables let race conditions leave a single retailer simultaneously liking and disliking the same product.
  • Running SELECT COUNT(*) per product on search pages: Counting 48 popular products per page at 350 searches/s scans millions of rows per second and melts the database.
  • Exposing a POST /toggle write endpoint or appending one row per click: Network retries flip reactions backward or insert duplicate likes that inflate counters.
  • Inserting placeholder NONE rows on DELETE requests for untouched products: Ensure DELETE (new_type = 0) checks whether a row exists before locking so bots or defensive client calls cannot bloat the table with dead NONE rows.
  • Dual-writing to PostgreSQL and INCR-ing Redis in application servers: Any crash or timeout between the two network calls causes permanent counter drift.
  • Updating product_reaction_counts with plain UPDATE instead of an upsert (INSERT ... ON CONFLICT DO UPDATE): If a newly published product receives its first like before a catalog consumer pre-creates its zero row, a plain UPDATE matches 0 rows and silently loses the like.
  • Populating Redis cache misses with unconditional SET instead of SET ... NX: A slow cache-miss reader can overwrite a newer write-through count pushed by the counter worker milliseconds earlier.
  • Reading the searching retailer's own heart state from a lagging replica (causing a just-clicked heart to flash empty) or using OFFSET pagination on thousand-item liked lists instead of a (updated_at, product_id) cursor.

Follow-up questions

  • Suppose a featured catalog item suddenly attracts thousands of likes per minute. How do you prevent database lock contention and cache bottlenecks on that single product's counter? On the reaction write path, 10,000 retailers write 10,000 distinct (retailer_id, product_id) primary keys, so user transactions never contend on a shared lock. On the counter path, partitioning Kafka by product_id sends every event for that viral item to a single consumer that coalesces (sums in RAM) 1 second of deltas before executing 1 single SQL upsert—turning 10,000 likes/minute into just 60 database row updates/minute. Because summing integers in memory handles hundreds of thousands of events/s, one consumer almost never saturates; if extreme bot-proof scale ever exceeded one CPU core, shard the Kafka key across N sub-slots (product_id, hash(retailer_id) % N) writing to product_reaction_counts_sharded(product_id, slot) and sum the N slots when refreshing Redis. On the read side, a 2-second in-memory LRU cache (Least Recently Used cache) inside each search/reactions server absorbs hot Redis key reads, paired with per-retailer rate limits.
  • Product managers want buyers to sort search queries by most-liked items. How must your indexing pipeline evolve now that search ranking depends on reaction counts? Because the search engine must rank all 50,000 matching catalog items before returning the top 48, like_count must now live inside the search index (such as an Elasticsearch doc-values numeric field). To avoid re-indexing documents on every single click, a search-indexer consumer reads count updates and flushes bulk partial updates every 2–5 minutes—and only when a product's count crosses a meaningful threshold (such as changing by ≥ 5% or crossing a logarithmic bucket floor(log2(likes + 1))), while the final 48 returned items still get fresh exact display counts from Redis. For hybrid "relevance, then popularity" queries, an even cheaper pattern retrieves the top 500 matches by text relevance and re-ranks those 500 in memory using cached Redis counts; product-wise, a time-decayed like velocity or conversion-weighted score should be A/B tested against raw lifetime likes so old catalog items do not freeze out new arrivals.
  • Brands request a time-series chart of daily likes segmented by buyer store category. Should that query hit your primary transactional database or a separate analytical store, and why? Build an analytical pipeline in a columnar data warehouse or OLAP store (an analytical database like ClickHouse, BigQuery, or Snowflake optimized for fast aggregations over millions of historical events), never on the transactional PostgreSQL store. First, reactions stores only the latest state per pair—if a boutique liked a candle on Monday and un-liked it on Wednesday, Monday's historical like no longer exists in reactions! Second, scanning millions of rows grouped by date and joined against retailer attributes would starve live traffic. Instead, sink the existing "reaction-changes" Kafka stream as an immutable append-only event log (event_id, retailer_id, product_id, brand_id, before_type, after_type, event_ts), join each event with the retailer's segment as of event_ts (boutique, salon, gift shop), and maintain hourly/daily rollup tables (brand_id, product_id, day, retailer_segment, likes_added, likes_removed, net_likes) for instant dashboard queries.
  • Following a partial infrastructure incident, precomputed product totals drift out of sync with the underlying reaction rows. How do you audit for discrepancies and reconcile counts without racing live traffic? For detection, run a nightly reconciliation query on an isolated read replica (or warehouse snapshot) that computes COUNT(*) FILTER (WHERE type = 1) and FILTER (WHERE type = 2) grouped by product_id over reactions, comparing against product_reaction_counts while excluding products whose updated_at is within the last 10 minutes so normal in-flight pipeline lag is never flagged as drift (after an outage, scope immediately to products updated during the incident window). For safe repair without race conditions, never overwrite product_reaction_counts directly from a batch script while live deltas are flowing; instead, emit a ReconcileProduct(product_id) command into the same product_id-keyed Kafka partition so the product's single-writer counter consumer verifies no reaction occurred in the past 10 minutes (and its own lag is < 10 minutes), overwrites the exact truth count in PostgreSQL, and refreshes Redis. If drift is widespread across millions of products, perform a clean snapshot-and-replay rebuild: compute a fresh product_reaction_counts_v2 table from a consistent PostgreSQL snapshot at WAL position L_0, replay Kafka events strictly after L_0 into _v2 until caught up, atomically swap table names, and overwrite affected Redis keys.

Follow-up questions

Similar questions

More Faire interview questions

All 10 Faire questions →