Design a Scalable Food-Item Review and Voting Platform
System DesignModel answerLast updated
Design a scalable review, rating, and vote tracking service for a food ordering platform, focusing on data modeling, atomic vote mutations, and read/write path performance.
Design an end-to-end review and community feedback system for a food delivery platform. Verified buyers can leave a star rating (0–5) and a written review for items on a restaurant's menu. Platform users can upvote or downvote existing reviews to flag helpful feedback.
Key Requirements
1. Business & Functional Scope
- Verified Reviews: Only users who have purchased an item can review it. Each user is restricted to at most one review per item.
- Ratings vs. Votes: Ratings (0 to 5 stars) belong to an item review. Upvotes and downvotes (+1 / -1) belong to other users evaluating the review's quality.
- Mutable Voting: A user can toggle their vote on a review (e.g., change an upvote to a downvote, or revoke a vote completely).
- Item Summary & Pagination: Item detail pages require the item's average star rating, total review count, and a paginated list of reviews (sorted by helpfulness or date).
2. Scale & Workload Profile
- Reviews: ~10,000 new reviews daily (~0.12 RPS baseline, low write rate).
- Votes & Ratings: ~1,000,000 requests per day for votes and rating updates (average ~12 RPS, peak ~100 RPS).
- Read/Write Mix: Review listing is read-heavy (99:1 read/write ratio). Rating and vote requests have an approximate 50:50 read/write balance.
Technical Deliverables
- Data Model & Schema: Define core tables/entities, primary and secondary keys, unique constraints, and eligibility checks.
- API Specification: Define endpoints for creating a review, voting on a review, and fetching an item detail page with reviews.
- Consistency & Concurrency: Detail how vote counters and item rating aggregates are updated accurately under concurrent requests (handling retries, vote flips, and cache evictions).
- Caching & Storage Strategy: Propose a storage architecture that maintains high read throughput without introducing write bottlenecks on hot menu items.
Hints
Hint 1
Use database unique constraints (e.g., composite primary keys or unique index on (user_id, item_id)) to enforce single-review and single-vote invariants natively.
Hint 2
Avoid recalculating average ratings on every request; maintain running totals (sum of stars and count of ratings) or use asynchronous stream processing to update aggregates.
Hint 3
For vote count changes (upvote -> downvote), handle delta updates explicitly (+2/-2 for vote flips) to prevent race conditions during concurrent requests.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. High-Level Architecture Overview
The system consists of three primary components: an API Gateway / Application Service layer, a Relational Database (durable single source of truth), and a Caching / Aggregation layer (Redis and asynchronous stream consumers).
+-------------------+
| Client / App |
+---------+---------+
|
v
+-------------------+
| API Gateway |
+---------+---------+
|
+--------------------+--------------------+
| |
v v
+-----------------------+ +---------------------+
| Review & Rating Svc | | Voting Service |
+-----------+-----------+ +----------+----------+
| |
+-----+-----+ +-----+-----+
| | | |
v v v v
+-------+ +-------+ +-------+ +-------+
| RDBMS | | Redis | | RDBMS | | Kafka |
+-------+ +-------+ +-------+ +---+---+
|
v
+---------------------+
| Async Aggregator |
+---------------------+
2. Data Modeling & Storage Strategy
We use a relational database (e.g., PostgreSQL) for durable transactional integrity, leveraging unique composite indexes to enforce business constraints natively at the storage engine level.
Database Schema (Relational DDL)
-- Track verified menu item purchases
CREATE TABLE order_items (
order_id UUID NOT NULL,
user_id UUID NOT NULL,
item_id UUID NOT NULL,
purchased_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (user_id, item_id, order_id)
);
-- Reviews table: one review per user per item
CREATE TABLE item_reviews (
review_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
item_id UUID NOT NULL,
user_id UUID NOT NULL,
rating SMALLINT NOT NULL CHECK (rating BETWEEN 0 AND 5),
comment TEXT,
upvote_count INT NOT NULL DEFAULT 0,
downvote_count INT NOT NULL DEFAULT 0,
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT uq_user_item_review UNIQUE (user_id, item_id)
);
CREATE INDEX idx_item_reviews_pagination
ON item_reviews (item_id, upvote_count DESC, created_at DESC);
-- Mutable user votes on reviews
CREATE TABLE review_votes (
review_id UUID NOT NULL REFERENCES item_reviews(review_id),
user_id UUID NOT NULL,
vote_type SMALLINT NOT NULL CHECK (vote_type IN (-1, 1)), -- +1 for upvote, -1 for downvote
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (review_id, user_id)
);
-- Denormalized item aggregate statistics
CREATE TABLE item_rating_stats (
item_id UUID PRIMARY KEY,
total_stars BIGINT NOT NULL DEFAULT 0,
total_reviews INT NOT NULL DEFAULT 0,
updated_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
Enforcing Constraints
- Purchase Eligibility: Before inserting into
item_reviews, queryorder_itemsfor a matching(user_id, item_id). - Single Review Constraint: Handled by
UNIQUE (user_id, item_id)onitem_reviews. Duplicate insert attempts trigger a unique constraint violation database error. - Single Vote Constraint & Mutability: Handled by
PRIMARY KEY (review_id, user_id)onreview_votes. Submitting a new vote uses anUPSERTstatement (INSERT ... ON CONFLICT DO UPDATE).
3. API Specifications
POST /v1/items/{item_id}/reviews
Submits a new review for an item.
- Request Body:
{ "user_id": "usr_123", "rating": 5, "comment": "Great spicy flavor, highly recommended!" } - Response:
201 Createdwith review details, or403 Forbidden(if not purchased), or409 Conflict(if user already reviewed this item).
POST /v1/reviews/{review_id}/vote
Cast, change, or rescind a vote on a review.
- Request Body:
{ "user_id": "usr_456", "vote_type": 1 // 1 = upvote, -1 = downvote, 0 = remove vote } - Response:
200 OKwith updated review vote counts.
GET /v1/items/{item_id}/reviews
Fetch item summary and paginated reviews.
- Query Params:
page_size=10,cursor=eyJ2b3RlcyI6MTUsImlkIjoiYWJjIn0=,sort_by=helpfulness - Response:
{ "item_id": "itm_789", "average_rating": 4.6, "total_reviews": 120, "reviews": [ { "review_id": "rev_001", "user_id": "usr_123", "rating": 5, "comment": "Great spicy flavor...", "upvotes": 15, "downvotes": 1, "created_at": "2023-10-24T12:00:00Z" } ], "next_cursor": "eyJ2b3RlcyI6MTAsImlkIjoiZGVmIn0=" }
4. Write Paths & Concurrency Control
A. Creating/Updating a Review
When a user submits a review:
- Verify purchase in
order_items. - Execute transactional insertion:
BEGIN; INSERT INTO item_reviews (review_id, item_id, user_id, rating, comment) VALUES ($1, $2, $3, $4, $5); INSERT INTO item_rating_stats (item_id, total_stars, total_reviews) VALUES ($2, $4, 1) ON CONFLICT (item_id) DO UPDATE SET total_stars = item_rating_stats.total_stars + EXCLUDED.total_stars, total_reviews = item_rating_stats.total_reviews + 1, updated_at = CURRENT_TIMESTAMP; COMMIT; - Invalidate or update the Redis cache key
item:rating_stats:{item_id}.
B. Voting & Vote Mutations (Upvote <-> Downvote)
A user vote transition can be one of three operations:
- New Vote (None -> Upvote or Downvote)
- Vote Change (Upvote -> Downvote, or vice versa)
- Vote Rescission (Upvote/Downvote -> None)
Handling state changes idempotently with SQL UPSERT:
WITH existing AS (
SELECT vote_type FROM review_votes
WHERE review_id = $1 AND user_id = $2
),
upsert AS (
INSERT INTO review_votes (review_id, user_id, vote_type)
VALUES ($1, $2, $3)
ON CONFLICT (review_id, user_id)
DO UPDATE SET
vote_type = EXCLUDED.vote_type,
updated_at = CURRENT_TIMESTAMP
RETURNING (SELECT vote_type FROM existing) AS old_vote
)
SELECT old_vote FROM upsert;
Based on the delta between old_vote and new_vote:
- New Upvote (
old_vote= NULL,new_vote= 1):upvote_count + 1 - Flip to Downvote (
old_vote= 1,new_vote= -1):upvote_count - 1, downvote_count + 1 - Flip to Upvote (
old_vote= -1,new_vote= 1):upvote_count + 1, downvote_count - 1 - Remove Vote (
old_vote= 1,new_vote= 0):upvote_count - 1
Update the parent item_reviews row atomically using delta increments:
UPDATE item_reviews
SET upvote_count = upvote_count + $delta_up,
downvote_count = downvote_count + $delta_down
WHERE review_id = $1;
5. Read Path & Cache Architecture
To maintain high read performance, we implement a Cache-Aside strategy backed by Redis.
Get Item Page Request
|
v
+----------------+
| Is Cached in |--- Yes ---> Return JSON Response
| Redis? |
+--------+-------+
| No
v
+----------------+
| Fetch from |
| Postgres DB |
+--------+-------+
|
v
+----------------+
| Write to Redis |
| (TTL = 1 hour) |
+--------+-------+
|
v
Return JSON Response
Cache Entities
- Item Summary Cache:
item:stats:{item_id}-> Hash containingaverage_rating,total_reviews. - Review List Page Cache:
item:reviews:{item_id}:page:{page_num}-> Rendered review JSON payload (TTL = 5–15 minutes).
Handling Cache Eviction & Hot Keys
- Cache Eviction Policy: If Redis evicts keys under memory pressure, the system falls back to database reads.
- Hot Items / Viral Reviews: For viral items receiving high read traffic, set up a Redis Read Replica Pool or local in-memory LRU cache at the API Gateway level to avoid cache stampedes (using single-flight/mutex locks during cache recomputation).
Pagination Architecture
We use Cursor-Based Pagination (keyset pagination) rather than OFFSET/LIMIT to guarantee stable rendering when votes or new reviews arrive continuously:
SELECT review_id, user_id, rating, comment, upvote_count, created_at
FROM item_reviews
WHERE item_id = $1
AND (upvote_count, created_at, review_id) < ($last_upvotes, $last_created_at, $last_id)
ORDER BY upvote_count DESC, created_at DESC, review_id DESC
LIMIT 10;
6. Scaling & Operational Trade-offs
Workload Capacity Planning
- Daily Volume: 10,000 new reviews, 1,000,000 vote/rating requests.
- RPS Calculation:
- Reviews: $10,000 / 86,400 \approx 0.12$ writes/sec.
- Votes / Ratings: $1,000,000 / 86,400 \approx 11.6$ requests/sec average.
- Peak factor ($5\times$ to $10\times$): Peak vote traffic $\approx 100$ RPS.
- Database Load: These throughput requirements are easily sustained by a modest single PostgreSQL instance if properly indexed.
Asynchronous Vote Aggregation (High-Throughput Variation)
If vote traffic spikes drastically (e.g., millions during a live marketing push), direct synchronously updating counters in the DB can lock rows excessively.
- Async Pipeline:
- API service writes vote events directly to Kafka:
Topic: review-votes. - Workers batch updates per review ID over a 1-second window.
- Workers execute bulk increment updates to PostgreSQL:
UPDATE item_reviews SET upvote_count = upvote_count + batch_upvotes WHERE review_id = target_review_id;
- API service writes vote events directly to Kafka:
- Trade-off: Eventual consistency for vote counts (1–2 second lag) in exchange for decoupling write throughput from DB lock contention.
7. Trade-offs & Common Pitfalls
| Design Choice | Pros | Cons |
|---|---|---|
| Synchronous Aggregation | Immediate consistency; simplicity in write path. | Higher DB lock contention on hot reviews under high vote concurrency. |
| Async Stream Aggregation | Exceptional write scalability; handles extreme spikes. | Eventual consistency; added operational complexity (Kafka + consumers). |
| Offset Pagination | Easy to implement client-side. | Degrades in performance on large offsets; produces skipped/duplicate items as new data streams in. |
| Cursor Pagination | Consistent performance ($O(1)$ lookup via index); stable ordering. | Cannot jump directly to arbitrary page numbers (e.g., page 42). |