Menu Dish Reviews, Star Ratings, and Mutable Vote Counters

Medium · System Design · Software Engineer · Onsite

Prompt

Architect the backend for a menu-dish feedback service serving a single restaurant whose single menu offers multiple dishes. Verified buyers of a dish can post a rating and optional written feedback, while readers can give each written review a thumbs-up or thumbs-down. Each dish view surfaces the dish title, photo, mean score, paginated customer comments, and per-comment thumbs-up and thumbs-down tallies (client-side star UI rendering is out of scope).

Honor the following domain rules and workload bounds:

  • Scores vs. review reactions: Dish scores span integers 0 through 5 inclusive (where 0 is an explicit zero-star score), kept completely distinct from helpfulness reactions on written reviews.
  • Per-user uniqueness & mutability: A buyer may hold at most one review record per dish (and may edit or remove it later). Likewise, a reader may hold at most one active reaction per review, with support for flipping an existing thumbs-up to a thumbs-down (or vice versa) and retracting a reaction.
  • Traffic profile: Roughly 10,000 new written reviews arrive each day. Reaction traffic and dish-score traffic each run around 1,000,000 requests per day (daily totals, not per-second throughput). Written-review views far outnumber submissions, whereas dish-score traffic splits roughly 50% reads and 50% writes.
  • Listing & roadmap: Serve a compact initial batch of comments on the dish view alongside deterministic sorting and multi-page navigation. Creator cash incentives tied to review votes may arrive in a later milestone, though reward formulas and payouts remain outside this initial scope.

Scope & Expectations

  • Data model, buyer verification & concurrency invariants: Model dishes, purchase verification, per-buyer dish reviews, and per-reader review reactions cleanly (without redundant ownership link tables), keeping dish score sums/counts and two-way vote tallies exact across edits, flips, retries, and concurrent requests.
  • Pagination & eviction-safe read caching: Deliver a small initial comment slice plus stable sorted pagination, backed by durable ground-truth tables and a cache layer that survives key evictions without dropping committed counts.
  • Capacity math, hot-row isolation & auditability: Convert daily review, score, and reaction volumes (and their read/write splits) into peak rates, index growing vote tables efficiently, mitigate lock contention on viral reviews via bounded aggregation with stated staleness trade-offs, and reconcile derived totals against raw records.

Step-by-step walkthrough

  1. Clarify requirements and scope

    All traffic serves one restaurant's menu, and daily volume sits near a million rating calls and a million vote calls per 24-hour day (rather than per second), so raw fleet QPS is modest. The real engineering challenge is keeping mutable counters exact under edits, vote flips, retries, and concurrent clicks. Before drawing boxes, state the functional rules and service goals clearly.

    Functional requirements

    • Item page: displays the item's name, image URL, average rating, total rating count, an initial small page of written reviews (5 reviews), each review's upvote and downvote counts, and how the current viewer voted on those reviews. Frontend star rendering is out of scope.
    • Ratings (0 to 5): integers 0, 1, 2, 3, 4, 5. Crucially, 0 is a valid rating, not "missing." Absence of a rating is represented by having no row (or a soft-deleted row).
    • One review record per user per item: a single (item_id, user_id) record holds the user's integer rating and optional review text (body). Why combine them? Because each user can review an item at most once, and ~500,000 rating writes/day vs. 10,000 written reviews/day means most buyers tap a quick star rating after delivery without typing text. Rating-only rows (body IS NULL) count toward the item's average rating, while only rows with text (body IS NOT NULL) appear in the review list.
    • Purchase eligibility: only a user who has received a delivered order containing that item may submit a rating or review. (Assume a later refund does not delete an existing review; content moderation hides abusive posts.)
    • Edits and deletes: authors can edit their rating or text, or delete their review, and the item's rating sum and count must update accurately.
    • Mutable review votes: a signed-in user (other than the review's author) may hold at most one active vote (up or down) per review, flip up -> down or down -> up, or remove their vote (none).
    • Ordering and pagination: show 5 written reviews initially on the item page, then paginate 10 per page sorted by newest or helpful.
    • Future extensibility: vote-based creator rewards are out of scope for launch, so we do not build payout pipelines yet, but we preserve per-user vote records and timestamps so future reward audits have complete ground truth.

    Non-functional requirements

    • Durability and counter accuracy: a confirmed rating or vote is never lost, even if a cache server restarts. Displayed counters may trail by a few seconds for other viewers, but must converge to the exact database truth.
    • Read-your-own-writes: a user who just rated an item or flipped a vote immediately sees their updated state.
    • Latency and availability: item page server latency p99 (the 99th percentile, meaning 99 out of 100 requests finish faster than this) under 200 ms; 99.9% read availability.
  2. Back-of-the-envelope numbers

    A day has 86,400 seconds. Converting daily numbers into per-second rates immediately tells us what hardware we need and where bottlenecks actually hide:

    Workload                        Daily volume           Average rate     10x dinner-rush peak
    --------------------------------------------------------------------------------------------
    Written reviews (writes)        10,000 / day           0.12 writes/s    ~1.2 writes/s
    Rating traffic (50/50 R/W mix)  1,000,000 / day
      - Rating writes (add/edit)    500,000 / day          5.8 writes/s     ~58 writes/s
      - Rating summary reads        500,000 / day          5.8 reads/s      ~58 reads/s
    Vote traffic (~1M req/day)
      - Conservative write bound    up to 1,000,000 / day  11.6 writes/s    ~116 writes/s
    Review / item page reads        assume 2,000,000 / day 23.1 reads/s     ~230 reads/s
      (review reads >> writes)
    
    Menu size                       ~100 items on one restaurant menu
    Uncached DB reads at peak       ~230 page views/s x 4 indexed queries = ~920 queries/s
    
    Storage growth (worst case: every write inserts a brand-new row)
      - review table                500k/day x 150 B + 10k/day x 1 KB text  ~85 MB/day (~31 GB/yr)
      - review_vote table + index   1M/day x 100 B                          ~100 MB/day (~37 GB/yr,
                                                                             ~365M rows/yr)
    

    Three architectural conclusions fall straight out of this math:

    1. No database sharding is needed. ~175 writes/s and ~920 uncached reads/s at peak easily fit on a single PostgreSQL primary server paired with one synchronous standby (a backup database that confirms every write before the client gets "OK," ensuring zero data loss on crash) and one read replica (a copy that serves read queries).
    2. Hot-row lock contention—not total QPS—is the real write bottleneck. Because one restaurant has only ~100 items and a funny or controversial review can go viral, many concurrent votes can hit the exact same counter row. In PostgreSQL, an UPDATE holds a row-level lock (a mutex on that single row so two transactions cannot overwrite each other) until the transaction commits. If commit + standby replication takes 2 to 5 ms, one row can serialize at most 1 / 0.005 = 200 to 1 / 0.002 = 500 updates/s. At 116 peak vote writes/s, direct counter updates work at launch, and we need a clean batching upgrade path for viral spikes.
    3. Never count votes with COUNT(*) on page reads. Within a year, review_vote holds hundreds of millions of rows. Scanning thousands of vote rows on every page load wastes CPU and memory; pre-aggregated counter rows make reads O(1).
  3. API design

    Design write endpoints to be idempotent—meaning if a mobile app loses signal and sends the exact same request twice, the second copy has the exact same effect as the first instead of double-counting. We achieve this by sending the desired target state (PUT with value: "down"), never a relative delta (POST /downvote):

    # Shared item page (cacheable across all viewers)
    GET    /v1/items/{item_id}?sort=helpful
           -> 200 {item_id, name, image_url,
                   rating: {average: 4.42, count: 1280},
                   reviews: [first 5 reviews with upvotes/downvotes],
                   next_cursor: "..."}
    
    # Subsequent review pages (cursor pagination, 10 per page)
    GET    /v1/items/{item_id}/reviews?sort=newest|helpful&limit=10&cursor=...
           -> 200 {reviews: [{review_id, author_name, rating, body, created_at,
                              upvotes, downvotes}], next_cursor: "..."}
    
    # Lightweight rating-only endpoint (serves the 50/50 rating widget/menu traffic)
    GET    /v1/items/{item_id}/rating
           -> 200 {item_id, average: 4.42, count: 1280, my_rating: 5 | null}
    
    # Viewer-specific vote state (never stored in a shared public cache)
    GET    /v1/items/{item_id}/reviews/my-votes?review_ids=101,102,103,104,105
           -> 200 {votes: {"101": "up", "102": "none", ...}}
    
    # Create or update the caller's single rating/review for this item
    PUT    /v1/items/{item_id}/review
           Headers: If-Match: <version> (optional optimistic concurrency check)
           Body:    {rating: 0..5, body: string | null}
           -> 200 {review_id, rating, body, version}
           -> 403 not_eligible | 409 version_conflict | 422 invalid_rating
    
    # Soft-delete the caller's review and remove its rating from the item aggregate
    DELETE /v1/items/{item_id}/review
           -> 200 {deleted: true}
    
    # Set or clear the caller's current vote on a review
    PUT    /v1/reviews/{review_id}/vote
           Body:    {value: "up" | "down" | "none"}
           -> 200 {review_id, value, upvotes, downvotes}
           -> 403 cannot_vote_own_review | 404 review_not_found
    

    Why split GET /v1/items/{item_id} from GET .../my-votes? The item summary and review list are identical for every visitor, so one cached entry serves thousands of readers. Only the tiny my-votes lookup depends on user_id. Also, on the client side, the app keeps at most one vote PUT in flight per review and retries only the user's latest tap so an old delayed retry of "up" cannot arrive after a newer "down".

  4. Data model

    Skip extra mapping tables like user_reviews or item_reviews. Ownership lives directly on the natural keys (keys formed by the real-world entities themselves): (item_id, user_id) uniquely identifies a review, and (review_id, user_id) uniquely identifies a vote.

    CREATE TABLE item (
      item_id    BIGINT PRIMARY KEY,
      name       TEXT NOT NULL,
      image_url  TEXT NOT NULL
    );
    
    -- Pre-aggregated rating totals per item (1 small row per item, initialized on item creation)
    CREATE TABLE item_rating (
      item_id       BIGINT PRIMARY KEY REFERENCES item (item_id),
      rating_sum    BIGINT NOT NULL DEFAULT 0,
      rating_count  BIGINT NOT NULL DEFAULT 0,
      CHECK (rating_sum >= 0 AND rating_count >= 0)
    );
    
    -- Populated from delivered-order events; proves a user bought an item
    CREATE TABLE purchase_eligibility (
      user_id         BIGINT NOT NULL,
      item_id         BIGINT NOT NULL REFERENCES item (item_id),
      first_order_id  BIGINT NOT NULL,
      purchased_at    TIMESTAMPTZ NOT NULL,
      PRIMARY KEY (user_id, item_id)
    );
    
    -- Source of truth for both star ratings and written reviews
    CREATE TABLE review (
      review_id   BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
      item_id     BIGINT NOT NULL,
      user_id     BIGINT NOT NULL,
      rating      SMALLINT NOT NULL CHECK (rating BETWEEN 0 AND 5),
      body        TEXT,                             -- NULL = rating-only, excluded from review lists
      status      TEXT NOT NULL DEFAULT 'visible'   -- visible | deleted | hidden (moderation)
                  CHECK (status IN ('visible', 'deleted', 'hidden')),
      rank_score  DOUBLE PRECISION NOT NULL DEFAULT 0, -- frozen "helpful" score refreshed periodically
      created_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
      updated_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
      version     INT NOT NULL DEFAULT 1,
      UNIQUE (item_id, user_id),                    -- enforces at most 1 review per user/item
      FOREIGN KEY (user_id, item_id)                -- enforces purchase eligibility in the DB
        REFERENCES purchase_eligibility (user_id, item_id)
    );
    
    -- Partial indexes: index only visible written reviews (~10k/day, skipping ~490k/day rating-only rows)
    CREATE INDEX review_newest_idx  ON review (item_id, created_at DESC, review_id DESC)
      WHERE body IS NOT NULL AND status = 'visible';
    CREATE INDEX review_helpful_idx ON review (item_id, rank_score DESC, review_id DESC)
      WHERE body IS NOT NULL AND status = 'visible';
    
    -- Separated vote counters per review (prevents votes from locking the review text/rating row)
    CREATE TABLE review_stats (
      review_id  BIGINT PRIMARY KEY REFERENCES review (review_id),
      upvotes    BIGINT NOT NULL DEFAULT 0,
      downvotes  BIGINT NOT NULL DEFAULT 0,
      CHECK (upvotes >= 0 AND downvotes >= 0)
    );
    
    -- Durable source of truth for per-user votes
    CREATE TABLE review_vote (
      review_id   BIGINT NOT NULL REFERENCES review (review_id),
      user_id     BIGINT NOT NULL,
      value       SMALLINT NOT NULL CHECK (value IN (-1, 0, 1)), -- 1=up, -1=down, 0=retracted
      updated_at  TIMESTAMPTZ NOT NULL DEFAULT now(),
      PRIMARY KEY (review_id, user_id)              -- enforces 1 current vote per user/review
    );
    

    Notice four deliberate schema choices:

    • Database-enforced invariants: UNIQUE (item_id, user_id), PRIMARY KEY (review_id, user_id), and the composite foreign key (a database rule requiring a matching row in purchase_eligibility) guarantee that even if two app servers race at the exact same millisecond, neither duplicate reviews nor unverified reviews can ever be inserted.
    • Integer rating_sum and rating_count instead of a floating-point average: floats accumulate rounding drift and cannot be updated when a user edits a rating unless you also know the count.
    • Counters separated from review: review_stats holds only two 8-byte integers per review. Heavy voting on a popular review never blocks the author from editing their review text, and partial indexes on review ignore rating-only rows so review list queries stay tiny and fast.
    • Soft deletes (status = 'deleted') and value = 0 for retracted votes: hard-deleting a review row would either fail on foreign keys from review_vote or wipe out vote history needed for future reward auditing.
  5. High-level architecture

      Mobile / Web Client
         |            \
         | images      \ API requests (HTTPS)
         v              v
     +-------+    +---------------+      +------------------------+      +-------------------+
     |  CDN  |    |  API Gateway  | ---> | Review & Vote Service  | <--> |   Redis Cache     |
     +-------+    | (auth, limits)|      | (stateless instances)  |      | (disposable copy) |
         ^        +---------------+      +------------------------+      +-------------------+
         |                                    |              |
     +--------------+           writes (SQL)  |              |  cache-miss reads
     | Object Store |                         v              v
     +--------------+              +--------------------+  +--------------------+
                                   | PostgreSQL Primary |->| PostgreSQL Replica |
                                   | (+ Sync Standby)   |  | (async read scale) |
                                   +--------------------+  +--------------------+
                                      ^       ^       ^
          "order.delivered" events    |       |       | Phase 2 batch fold (hot reviews)
       +-----------------------+      |       |   +----------------------+
       | Eligibility Consumer  |------+       +---| Vote Delta Aggregator|
       +-----------------------+                  +----------------------+
                                                  +----------------------+
                                                  | Nightly Reconciler   |
                                                  +----------------------+
    
    • PostgreSQL is the single source of truth. Every accepted rating, review, and vote commits to the primary before we return 200 OK.
    • Redis is a cache-aside read cache (an external memory store where readers check Redis first, query Postgres on a miss, and populate Redis with an expiration timer). Redis never holds unpersisted increments, so losing or evicting a Redis key never loses data.
    • Order Eligibility Consumer listens to "order.delivered" events from the order system and runs INSERT INTO purchase_eligibility ... ON CONFLICT (user_id, item_id) DO NOTHING, making duplicate events harmless.
  6. Deep dive 1: Mutable votes and exact two-counter updates

    Watch out for the classic two-counter trap: flipping an existing thumbs-up to a thumbs-down touches both counters at once, unlike casting a fresh thumbs-down from scratch. When a reader switches from up (+1) to down (-1), upvotes must decrease by 1 and downvotes must increase by 1. Every transition between none (0), up (1), and down (-1) maps to an exact (up_delta, down_delta) pair:

    Old vote  -->  New vote     up_delta    down_delta    Why
    ------------------------------------------------------------------------------------
    none (0)  -->  up   (+1)       +1           0         Brand-new upvote
    none (0)  -->  down (-1)        0          +1         Brand-new downvote
    up  (+1)  -->  down (-1)       -1          +1         Remove old upvote AND add downvote
    down(-1)  -->  up   (+1)       +1          -1         Remove old downvote AND add upvote
    up  (+1)  -->  none  (0)       -1           0         Retract upvote
    down(-1)  -->  none  (0)        0          -1         Retract downvote
    same      -->  same             0           0         Retry or double-tap (no-op)
    

    To compute those deltas safely when a user double-taps from two devices at once, we must lock that user's review_vote row inside the same database transaction that updates review_stats:

    def compute_vote_deltas(old_value: int, new_value: int) -> tuple[int, int]:
        """Return (up_delta, down_delta) when transitioning from old_value to new_value."""
        up_delta = 0
        down_delta = 0
        # Step 1: undo the effect of the previous vote, if any.
        if old_value == 1:
            up_delta -= 1
        elif old_value == -1:
            down_delta -= 1
        # Step 2: apply the effect of the new vote, if any.
        if new_value == 1:
            up_delta += 1
        elif new_value == -1:
            down_delta += 1
        return up_delta, down_delta
    
    
    def set_review_vote(db, caller_user_id: int, review_id: int, new_value: int) -> str:
        """Idempotently set caller_user_id's vote on review_id to -1, 0, or 1."""
        review = db.query_one(
            "SELECT user_id, body, status FROM review WHERE review_id = %s",
            (review_id,),
        )
        if review is None or review.status != "visible" or review.body is None:
            return "review_not_votable"
        if review.user_id == caller_user_id:
            return "cannot_vote_own_review"
    
        with db.transaction():
            # Ensure the (review_id, user_id) row exists with neutral value 0 so
            # SELECT ... FOR UPDATE always has a concrete row to lock.
            db.execute(
                "INSERT INTO review_vote (review_id, user_id, value) VALUES (%s, %s, 0) "
                "ON CONFLICT (review_id, user_id) DO NOTHING",
                (review_id, caller_user_id),
            )
            old_value = db.query_value(
                "SELECT value FROM review_vote "
                "WHERE review_id = %s AND user_id = %s FOR UPDATE",
                (review_id, caller_user_id),
            )
            if old_value == new_value:
                return "unchanged"  # Safe retry or duplicate tap: touch nothing.
    
            up_delta, down_delta = compute_vote_deltas(old_value, new_value)
            db.execute(
                "UPDATE review_vote SET value = %s, updated_at = now() "
                "WHERE review_id = %s AND user_id = %s",
                (new_value, review_id, caller_user_id),
            )
            db.execute(
                "UPDATE review_stats SET upvotes = upvotes + %s, downvotes = downvotes + %s "
                "WHERE review_id = %s",
                (up_delta, down_delta, review_id),
            )
        return "updated"
    

    Why the INSERT ... ON CONFLICT DO NOTHING before SELECT ... FOR UPDATE? If a user has never voted on this review before and two identical "up" requests arrive simultaneously, a plain SELECT in both transactions would see "no row," and one could fail or miscompute. With INSERT ... ON CONFLICT DO NOTHING, PostgreSQL makes the second transaction wait until the first commits, then SELECT ... FOR UPDATE reads old_value = 1, sees old_value == new_value, and exits cleanly without double-incrementing.

  7. Deep dive 2: Item rating sum, count, and edits (including 5 -> 0)

    Every item's average is calculated on read as rating_sum / rating_count (displaying "No ratings yet" when rating_count == 0). Every lifecycle transition adjusts rating_sum and rating_count by exact integers:

    Transition on (item_id, user_id)          rating_sum change        rating_count change
    --------------------------------------------------------------------------------------
    New visible review with rating r          + r                      + 1
    Edit visible review: old -> new           + (new - old)            0  (same rater!)
    Delete (or moderator hides) review        - old                    - 1
    Re-submit after user previously deleted   + new                    + 1
    Edit while hidden by moderator            0 (stays out of total)   0
    

    Walk through a concrete example: Item 42 currently has rating_sum = 45 and rating_count = 10 (45 / 10 = 4.50 average). One buyer edits their rating from 5 down to 0:

    • rating_sum becomes 45 + (0 - 5) = 40.
    • rating_count stays 10 (it is still 10 buyers, not 11, and 0 is a valid zero-star rating, not a deletion).
    • New average: 40 / 10 = 4.00.
    def upsert_review(db, user_id: int, item_id: int, rating: int, body: str | None) -> str:
        """Create or update (item_id, user_id) review and keep item_rating exact."""
        if rating < 0 or rating > 5:
            return "invalid_rating"
    
        with db.transaction():
            eligible = db.query_value(
                "SELECT 1 FROM purchase_eligibility WHERE user_id = %s AND item_id = %s",
                (user_id, item_id),
            )
            if eligible is None:
                return "not_eligible"
    
            # Try inserting first; ON CONFLICT DO NOTHING protects against concurrent creates.
            created_id = db.query_value(
                "INSERT INTO review (item_id, user_id, rating, body, status) "
                "VALUES (%s, %s, %s, %s, 'visible') "
                "ON CONFLICT (item_id, user_id) DO NOTHING RETURNING review_id",
                (item_id, user_id, rating, body),
            )
            if created_id is not None:
                db.execute("INSERT INTO review_stats (review_id) VALUES (%s)", (created_id,))
                db.execute(
                    "INSERT INTO item_rating (item_id, rating_sum, rating_count) "
                    "VALUES (%s, %s, 1) "
                    "ON CONFLICT (item_id) DO UPDATE SET "
                    "rating_sum = item_rating.rating_sum + EXCLUDED.rating_sum, "
                    "rating_count = item_rating.rating_count + 1",
                    (item_id, rating),
                )
                return "created"
    
            # Row already exists: lock it so concurrent edits serialize cleanly.
            old = db.query_one(
                "SELECT rating, status FROM review WHERE item_id = %s AND user_id = %s FOR UPDATE",
                (item_id, user_id),
            )
            # If the user previously deleted their review, restore it to 'visible';
            # if a moderator hid it ('hidden'), keep it 'hidden'.
            new_status = "visible" if old.status == "deleted" else old.status
            db.execute(
                "UPDATE review SET rating = %s, body = %s, status = %s, "
                "updated_at = now(), version = version + 1 "
                "WHERE item_id = %s AND user_id = %s",
                (rating, body, new_status, item_id, user_id),
            )
    
            if old.status == "deleted" and new_status == "visible":
                # Returning rater: add their new rating and +1 to count.
                db.execute(
                    "UPDATE item_rating SET rating_sum = rating_sum + %s, "
                    "rating_count = rating_count + 1 WHERE item_id = %s",
                    (rating, item_id),
                )
            elif old.status == "visible" and rating != old.rating:
                # Existing active rater: adjust sum by (new - old), count unchanged.
                db.execute(
                    "UPDATE item_rating SET rating_sum = rating_sum + %s WHERE item_id = %s",
                    (rating - old.rating, item_id),
                )
        return "updated"
    

    Notice we check rating < 0 or rating > 5 explicitly and never write if rating:—because in Python bool(0) is False, which would silently ignore a user changing their rating to 0! Similarly, DELETE /v1/items/{item_id}/review locks the row under FOR UPDATE, transitions 'visible' -> 'deleted', and subtracts old.rating from rating_sum and 1 from rating_count.

  8. Deep dive 3: Stable pagination and eviction-safe caching

    1. Cursor (keyset) pagination instead of OFFSET. SQL OFFSET 500 LIMIT 10 forces the database to scan and discard 500 rows, and if a new review arrives at the top while a user is reading page 1, row 5 gets pushed down to page 2 so the user sees it twice. Instead, we use keyset pagination—passing the sort values of the last row on the previous page as a bookmark (cursor):

    SELECT r.review_id, r.user_id, r.rating, r.body, r.created_at,
           s.upvotes, s.downvotes
    FROM review r
    JOIN review_stats s ON s.review_id = r.review_id
    WHERE r.item_id = $1
      AND r.body IS NOT NULL
      AND r.status = 'visible'
      AND (r.created_at, r.review_id) < ($2, $3)   -- cursor bookmark from previous page
    ORDER BY r.created_at DESC, r.review_id DESC
    LIMIT 10;
    

    Including review_id DESC as a unique tie-breaker guarantees a strict total order even when two reviews share the exact same microsecond timestamp, and review_newest_idx serves any page depth in a single B-tree seek plus 10 rows.

    2. Stable "Most helpful" sorting via a periodically frozen Wilson score. If we sorted directly by live upvotes - downvotes, a burst of votes would constantly shuffle rows across page boundaries while someone scrolls, and a brand-new 1 up / 0 down review (100% positive) would naively outrank a proven 95 up / 5 down review (95% positive) if sorted by raw ratio. Instead, a background worker refreshes review.rank_score every 10 minutes for reviews whose vote counts changed, using the Wilson score 95% confidence lower bound (a statistical formula that asks "given the sample size, what is the lowest plausible true upvote fraction?"):

    n = upvotes + downvotes,   p = upvotes / n,   z = 1.96  (for 95% confidence)
    rank_score = (p + z^2/(2n) - z * sqrt(p*(1 - p)/n + z^2/(4*n^2))) / (1 + z^2/n)
                 (and 0 when n == 0)
    
    Check:  1 up,  0 down  -> rank_score ~ 0.21
           95 up,  5 down  -> rank_score ~ 0.89   (ranks higher, as intuition expects!)
    

    Between 10-minute refreshes rank_score does not move, so keyset pagination on (rank_score DESC, review_id DESC) is fast and stable.

    3. Cache strategy that tolerates eviction. Redis stores only disposable copies of committed database state with short TTLs (time-to-live expiration timers):

    Redis key                   Cached payload                             TTL     Invalidated after commit of
    ---------------------------------------------------------------------------------------------------------
    item:{id}:summary           name, image_url, rating_sum, rating_count  5 min   upsert/delete review
    item:{id}:first:{sort}      first 5 review objects + next_cursor       60 s    written review add/edit/del
    review:{id}:counts          upvotes, downvotes                         30 s    vote change
    
    • Why eviction never loses votes: we never run write-back INCR in Redis as the source of truth. Postgres commits review_vote + review_stats first; then the app deletes review:{id}:counts in Redis. If Redis evicts the key under memory pressure or crashes completely, the next reader simply misses Redis, reads the single review_stats row by primary key from Postgres (O(1)), and repopulates Redis.
    • Preventing stale replica refills (delayed double delete): right after the primary commits and deletes the Redis key, a concurrent reader might miss Redis and read the 200-ms-stale read replica before replication catches up, writing the old count back into Redis for the full 5-minute TTL. Scheduling a second Redis DEL ~2 seconds later (longer than normal replica lag) clears any stale refill, while the TTL remains a safety net.
    • Read-your-own-writes: the PUT response returns the updated counts directly to the caller's UI, and for 10 seconds after a user writes, their my-votes / my_rating check routes to the primary instead of the replica.
  9. Scaling, hot-row batching, reconciliation, and failures

    1. Upgrading hot counter rows from synchronous (Phase 1) to batched asynchronous projection (Phase 2). Phase 1 updates review_stats inside set_review_vote, which handles ~200–500 votes/s on a single review. We emit a metric for votes per review_id per minute; if a viral review approaches ~100 votes/s, we flip Phase 2 on:

    • Inside set_review_vote, instead of updating review_stats directly (which contends on one review lock), the transaction locks only the voter's personal (review_id, user_id) row and inserts (review_id, up_delta, down_delta) into an append-only vote_delta table. Concurrent voters never block one another!
    • A single aggregator worker (guarded by a PostgreSQL advisory lock, an application-named mutex inside Postgres so only one worker runs at a time) folds up to 5,000 deltas every 1 second:
    def fold_vote_deltas(db, batch_size: int = 5000) -> list[int]:
        """Sum pending vote deltas per review and apply 1 update per review per batch."""
        with db.transaction():
            rows = db.query(
                "SELECT delta_id, review_id, up_delta, down_delta FROM vote_delta "
                "ORDER BY delta_id LIMIT %s FOR UPDATE",
                (batch_size,),
            )
            if not rows:
                return []
    
            up_totals: dict[int, int] = {}
            down_totals: dict[int, int] = {}
            delta_ids: list[int] = []
            for delta_id, review_id, up_delta, down_delta in rows:
                up_totals[review_id] = up_totals.get(review_id, 0) + up_delta
                down_totals[review_id] = down_totals.get(review_id, 0) + down_delta
                delta_ids.append(delta_id)
    
            # Sort review_ids so multiple updaters can never deadlock on lock order.
            touched_reviews = sorted(up_totals.keys())
            for review_id in touched_reviews:
                db.execute(
                    "UPDATE review_stats SET upvotes = upvotes + %s, "
                    "downvotes = downvotes + %s WHERE review_id = %s",
                    (up_totals[review_id], down_totals[review_id], review_id),
                )
            # Delete the exact delta_ids folded so late-committing lower IDs are never skipped.
            db.execute("DELETE FROM vote_delta WHERE delta_id = ANY(%s)", (delta_ids,))
        return touched_reviews
    
    • Declared consistency trade-off: in Phase 2, review_vote is strongly consistent immediately, the voter's own UI updates instantly from the PUT response, and other viewers see vote counts lag by ~1–3 seconds (1 s batch interval + replica lag), after which the aggregator invalidates review:{id}:counts.
    • Large vote-table indexing: PRIMARY KEY (review_id, user_id) covers all three hot queries: single-voter lookup in set_review_vote, 10-key lookup for my-votes, and per-review range scan during reconciliation. Once review_vote passes a few hundred million rows, hash-partition it into 16 partitions by review_id so B-tree indexes and vacuum stay compact.

    2. Nightly reconciliation. Because review_stats and item_rating are projections (derived summary tables), a nightly job verifies them on the read replica inside a single REPEATABLE READ transaction (a consistent point-in-time snapshot so all tables read within the transaction reflect the exact same instant):

    SELECT review_id,
           COUNT(*) FILTER (WHERE value =  1) AS expected_up,
           COUNT(*) FILTER (WHERE value = -1) AS expected_down
    FROM review_vote
    WHERE review_id BETWEEN $1 AND $2
    GROUP BY review_id;
    

    In that same snapshot, it reads review_stats plus any unapplied vote_delta sums for those reviews. If expected_up != (stats.upvotes + pending_up_delta), it alerts on-call (since any mismatch signals a code bug) and applies a relative fix upvotes = upvotes + drift on the primary so live votes arriving after the snapshot are preserved. Each night checks 1/30th of the ID range plus the day's top 1,000 voted reviews, and checks item_rating against SUM(rating), COUNT(*) of status = 'visible' reviews.

    3. Failure modes.

    • Redis outage or full cache flush: reads fall back to the read replica (~920 indexed queries/s at peak, easily handled by one Postgres instance) while a 1–2 second in-memory cache per app server absorbs the hottest menu items.
    • Primary database crash: promote the synchronous standby; zero committed ratings or votes are lost, and clients safely retry failed PUTs.
    • Order-delivered event delayed: if a buyer taps "Review" seconds after delivery before the event arrives, the review service queries the Order Service synchronously on cache/table miss, upserts purchase_eligibility, and proceeds instead of returning a false 403.

Intuition & how it works

Think of this system like a verified-buyer suggestion box with two live scoreboards: one scoreboard per menu item showing its star average, and one scoreboard per written review showing its upvotes and downvotes. Each customer gets one erasable ballot per item (their 0–5 rating and optional comment) and one movable magnet per review that they can place on the "Up" column, move to the "Down" column, or take off the board completely. Because moving a magnet from "Up" to "Down" changes both columns at once, you can only update the scoreboard accurately if you look at where that customer's magnet is sitting right now before you move it.

Two obvious beginner designs fail here in opposite ways. First, skipping the scoreboards and running SELECT COUNT(*) over the raw votes table on every page load gets slower precisely on the most popular reviews—scanning tens of thousands of rows hundreds of times per second. Second, keeping the scoreboards only as INCR / DECR counters in an in-memory cache like Redis loses votes whenever memory fills up and evicts a key, and double-counts whenever a flaky phone connection retries a vote.

Instead, we store each user's current state and the pre-computed integer scoreboards together in PostgreSQL, and treat Redis purely as a disposable read copy. Watch what happens across 4 events on Review 10 (starting at 0 up, 0 down) and Item 42 (starting at sum = 9, count = 2, average 4.50):

Event                                  Per-user truth row        Scoreboard update (same DB txn)
-------------------------------------------------------------------------------------------------
1. Alice taps Up on Review 10          vote(10, Alice): 0 -> +1  upvotes +1, downvotes +0 -> (1, 0)
2. Alice's phone retries Up            vote(10, Alice): +1 == +1 no change!               -> (1, 0)
3. Alice flips her vote to Down        vote(10, Alice): +1 -> -1 upvotes -1, downvotes +1 -> (0, 1)
4. Bob edits Item 42 rating: 5 -> 0    review(42, Bob):  5 ->  0 sum + (0 - 5) = 4, count = 2 (avg 2.00)

Notice how Step 2 does nothing because the API sends the target state ("up"), Step 3 subtracts the old upvote and adds the new downvote in one atomic step, and Step 4 adjusts rating_sum by new - old = -5 while keeping rating_count at 2.

Key trade-offs

  • Synchronous in-transaction counters vs. asynchronous batched counters. Updating review_stats inside the vote transaction (an all-or-nothing group of database statements) guarantees that the counter is exact the instant a vote succeeds, with zero extra worker processes. However, every concurrent vote on the same viral review must wait its turn on that single row's row-level lock (an exclusive lock held until commit, capping one row at ~200–500 updates/s). Switching hot reviews to an append-only vote_delta table folded once per second removes row contention completely, trading 1–3 seconds of count delay for other viewers in exchange for unbounded write throughput.
  • Integer rating_sum and rating_count vs. a stored floating-point average. Storing two integers per item requires dividing rating_sum / rating_count on read, but lets us apply additions (+r, +1), edits (+(new - old), +0), and deletions (-old, -1) with zero floating-point rounding drift. A stored float average cannot even compute an edit or deletion without also storing the count.
  • State-setting PUT APIs vs. delta POST events. Having clients send PUT {value: "down"} instead of POST /downvote makes the API naturally idempotent (safe to repeat without changing the result beyond the first call) without maintaining a separate idempotency-key lookup table. The trade-off is that every write must lock and read the user's previous row to compute the counter delta.
  • Database truth + disposable cache vs. write-back counters in Redis. In a write-back cache (where writes update cache memory first and flush to the database later), writes are sub-millisecond, but cache eviction (automatic removal of keys when memory is full) or an asynchronous Redis failover silently drops increments. At ~1M votes per day (~12/s average, ~116/s peak), PostgreSQL handles the writes effortlessly, so keeping Redis as a cache-aside copy (populated on read misses and deleted after database commits) gives fast reads with zero risk of lost votes.
  • Periodically frozen helpfulness score vs. live vote-count sorting. Recomputing rank_score every 10 minutes with a Wilson score lower bound (a confidence-adjusted upvote ratio that prevents a 1 up / 0 down review from beating 95 up / 5 down) means a review's rank lags live votes by up to 10 minutes, but prevents reviews from jumping across pages and duplicating while a user scrolls with keyset pagination (bookmarking the last seen (score, review_id) tuple instead of counting row OFFSETs).
  • Retaining retracted votes (value = 0) and soft-deleted reviews (status = 'deleted'). Keeping neutral/deleted rows uses slightly more disk space, but simplifies concurrency locking, avoids foreign-key deletion errors, and preserves the full audit trail needed if vote-based payouts launch later.

Common mistakes

  • Treating a vote flip (up -> down) as a single counter increment. Adding +1 to downvotes without subtracting -1 from upvotes leaves a phantom upvote forever. Always compute both up_delta and down_delta from (old_value, new_value).
  • Reading old_value outside SELECT ... FOR UPDATE. If two requests from the same user read old_value = 0 concurrently without locking the row, both see 0 -> +1 and increment upvotes twice.
  • Treating rating 0 as falsy or "unrated." Valid scores span integers 0 to 5 inclusive. Writing if rating: in Python or mapping 0 to "no rating" drops zero-star edits (5 -> 0) or miscounts them as deletions.
  • Confusing daily volume (~1M/day) with per-second load (~1M/s). 1,000,000 / 86,400 s is ~11.6 requests/s on average. Over-engineering multi-shard NoSQL clusters misses what the interviewer actually cares about: counter consistency, hot-row locks, and pagination stability.
  • Adding extra join tables (user_reviews, user_votes) for ownership. Maintaining a second mapping table alongside review(item_id, user_id) and review_vote(review_id, user_id) adds extra writes and risks the two tables drifting out of sync, when unique constraints on the natural keys already express ownership directly.
  • Hard-deleting reviews when foreign keys exist. If review_stats and review_vote reference review(review_id), a raw DELETE FROM review either crashes with a foreign-key violation or cascades away historical vote records. Soft-deleting (status = 'deleted') and decrementing item_rating in the same transaction is clean and reversible.

Follow-up questions

  • How does your architecture avoid losing vote updates if a cache entry is evicted prior to database persistence? In our design, Redis never holds unpersisted increments: every vote commits to PostgreSQL (review_vote plus review_stats, or vote_delta in Phase 2) before the request succeeds, and Redis only caches a read copy of review_stats that is deleted after commit. If Redis evicts review:{id}:counts or restarts completely, the next page view simply misses the cache, fetches the single review_stats row from PostgreSQL by primary key in O(1) time, and repopulates Redis with zero lost votes. Even if extreme scale ever forced caching increments ahead of review_stats, you would still write each per-user vote durably to an append-only log or database table first so evicted counters can always be reconstructed from ground truth.
  • Walk through how dish rating totals change when an existing buyer lowers their score from 5 down to 0. Inside one database transaction, lock the user's (item_id, user_id) row in review with SELECT ... FOR UPDATE, verify it is currently visible with old_rating = 5, update rating = 0, and update item_rating by adding new_rating - old_rating = 0 - 5 = -5 to rating_sum while leaving rating_count unchanged. For example, if the dish previously had rating_sum = 45 and rating_count = 10 (average 4.50), it becomes rating_sum = 40 and rating_count = 10 (average 4.00). Leaving rating_count unchanged is essential because 0 is a valid zero-star score from the same buyer, not a second review and not a deletion.
  • Even with an index on the votes table, why shouldn't each page view count all matching vote rows on the fly? A B-tree index on (review_id, user_id) lets the database jump to the first vote of a review quickly, but counting still has to walk through every matching entry for that review—making read work O(V) where V is the number of votes, rather than O(1). Worse, because (review_id, user_id) does not include value (and retracted votes have value = 0), the database must also visit table pages (or maintain a larger covering index) to separate 1, -1, and 0. Since the most popular reviews attract both the most votes (tens of thousands each) and the most page views, scanning 10 popular reviews per page view multiplies into hundreds of thousands of row reads per request, whereas reading review_stats fetches just 10 tiny rows by primary key.
  • When a single viral review attracts a sudden surge of concurrent vote flips, which write operation hits contention first? The UPDATE review_stats statement on that single popular review's counter row becomes the bottleneck, not review_vote. Every voter touches their own distinct (review_id, user_id) row in review_vote without conflicting with other users, but in Phase 1 all of those transactions must acquire the exclusive row lock on the same review_stats row and hold it until commit (~2–5 ms), serializing throughput at roughly 200–500 votes/s regardless of how many app servers you add. The fix (Phase 2) is to have vote transactions append (review_id, up_delta, down_delta) into an insert-only vote_delta table and let a single background aggregator sum and apply one UPDATE per review every second.

Follow-up questions

Similar questions

More DoorDash interview questions

All 241 DoorDash questions →