Design a Scalable Food Delivery Review Platform
System DesignModel answerLast updated
Design a backend architecture to capture, aggregate, and display diner reviews and media ratings at high volume with low read latencies.
Scenario
You are tasked with designing the backend infrastructure for a meal delivery platform's user feedback system. Customers routinely post rating scores, written commentary, and photos or videos after completing an order. Millions of prospective diners read these reviews every evening to decide where to order from.
Requirements
Functional Requirements
- Submit Feedback: Customers can publish a single review per completed order, consisting of a integer rating (1–5 stars), optional written text, and optional photos/videos.
- Display Restaurant Reviews: Prospective diners can view pages of published reviews for a given restaurant, with support for sorting by recency or by community helpfulness.
- Helpfulness Votes: Logged-in users can upvote or downvote existing reviews to highlight useful feedback.
Non-Functional Requirements
- Read Performance: The primary review page feed must return in under 200ms at $p_{99}$.
- High Write Availability: Submitting a review or casting a vote must accept writes smoothly during peak dinner hours without blocking or crashing application servers.
- Eventual Aggregation: Overall restaurant statistics (average stars, star counts, vote totals) can settle within seconds of submittal rather than requiring strict immediate transactions.
Deliverables
- API Specifications: Outline key HTTP or RPC contract endpoints for uploading media, persisting reviews, viewing reviews, and casting votes.
- Data Storage & Schema: Recommend a database technology stack and provide a relational or document table design.
- Media Pipeline: Explain how uploaded images and videos are securely handled without overloading application servers.
- Scale & Pagination: Detail how high-traffic "hotspot" restaurants are optimized for reads, including caching design and cursor-based pagination.
Hints
Hint 1
Decouple direct object storage file uploads from transactional database writes using signed temporary upload links.
Hint 2
Avoid offset-based pagination SQL queries on high-cardinality tables; use keyset composite cursors instead.
Hint 3
Decouple instantaneous write responses from aggregate statistic updates using transactional outbox events processed by background workers.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
System Architecture Overview
To support millions of daily orders and high-traffic discovery feeds, the review service separates fast read paths (served via Edge CDNs and Redis caches) from asynchronous write processing (backed by message queues and database workers).
+--------------------+
| Mobile / Web |
+---------+----------+
|
+----------------------+----------------------+
| Direct Upload | API Traffic
v v
+--------------------+ +--------------------+
| Object Storage | | API Gateway |
| (e.g., S3) | +---------+----------+
+---------+----------+ |
| v
| S3 Event +--------------------+
v | Review Service |
+--------------------+ +----+----------+----+
| Media Transcoder | | |
| Worker Pipeline | v v
+--------------------+ +------+ +--------+
|Redis | | Primary|
|Cache | | DB |
+------+ +---+----+
|
v
+--------+
| Event |
| Bus |
+---+----+
|
v
+--------+
| Aggreg.|
| Worker |
+--------+
1. Estimating Traffic & Resource Scale
To validate architectural choices, we start with back-of-the-envelope capacity estimations:
- Daily Orders: 20,000,000 completed orders/day.
- Review Rate: ~10% conversion $\rightarrow$ 2,000,000 reviews submitted per day.
- Write Throughput:
- Average: $\frac{2,000,000}{86,400} \approx 23 \text{ reviews/sec}$.
- Dinner Peak Spike (6x multiplier): $\approx 150 \text{ write requests/sec}$.
- Helpfulness Voting: ~5 votes cast per review $\rightarrow \approx 1,000 \text{ vote requests/sec}$ peak.
- Read-to-Write Ratio: ~100:1. Read requests reach $\approx 15,000 \text{ to } 20,000 \text{ QPS}$ at peak.
- Payload Estimates:
- Metadata & Text: ~1 KB per review payload $\rightarrow$ 2 GB text stored daily.
- Media: ~20% of reviews upload 1–2 photos (avg 500 KB optimized) $\rightarrow$ ~200 GB binary storage daily.
Key Insight: Binary asset transfers must be handled entirely out-of-band relative to core application instances. Read latency is protected through aggressive key-value caching and cursor-based database indexing.
2. API Design
Request Presigned Media Upload URL
POST /v1/media/upload-url
Content-Type: application/json
{
"content_type": "image/jpeg",
"size_bytes": 1048576
}
# Response: 200 OK
{
"media_id": "med_88f91a0b",
"upload_url": "https://storage.provider.com/raw-uploads/med_88f91a0b?Signature=...",
"expires_in_seconds": 900
}
Submit Review
POST /v1/reviews
Idempotency-Key: e4a2b918-971c-4022-b530-9b0d12e8412c
Content-Type: application/json
{
"order_id": 98120412,
"restaurant_id": 41209,
"rating": 5,
"text": "Food arrived hot and packaging was spotless!",
"media_ids": ["med_88f91a0b"]
}
# Response: 202 Accepted
{
"review_id": 1092830192,
"status": "PROCESSING"
}
Get Paginated Reviews
GET /v1/restaurants/41209/reviews?sort=helpful&limit=20&cursor=eyJzY29yZSI6OC41LCJpZCI6MTA5MjgzMDE5Mn0=
# Response: 200 OK
{
"restaurant_id": 41209,
"summary": {
"average_rating": 4.7,
"total_reviews": 840,
"rating_distribution": { "1": 10, "2": 15, "3": 35, "4": 180, "5": 600 }
},
"reviews": [
{
"review_id": 1092830192,
"author_name": "Jordan P.",
"rating": 5,
"text": "Food arrived hot and packaging was spotless!",
"media": [
{ "url": "https://cdn.platform.com/media/med_88f91a0b.jpg", "type": "image" }
],
"upvotes": 14,
"downvotes": 1,
"created_at": "2023-11-01T19:15:00Z"
}
],
"next_cursor": "eyJzY29yZSI6Ny4xLCJpZCI6MTA5MjgwMDAxMX0="
}
Cast or Modify Helpfulness Vote
PUT /v1/reviews/1092830192/votes
Content-Type: application/json
{
"vote_value": 1 // 1 = Upvote, -1 = Downvote, 0 = Clear
}
# Response: 200 OK
{
"review_id": 1092830192,
"user_vote": 1
}
3. Data Storage & Schema Design
Because we require transactional constraints to prevent duplicate reviews per order (order_id UNIQUE), combined with structured range queries for cursor pagination, a relational database (e.g., PostgreSQL) sharded horizontally by restaurant_id provides optimal consistency and query characteristics.
Primary Database Schema
CREATE TABLE reviews (
review_id BIGINT PRIMARY KEY, -- Time-sortable Snowflake ID
restaurant_id BIGINT NOT NULL,
order_id BIGINT UNIQUE NOT NULL, -- Enforces 1 review per completed order
user_id BIGINT NOT NULL,
rating SMALLINT CHECK (rating BETWEEN 1 AND 5),
text TEXT,
status VARCHAR(16) NOT NULL DEFAULT 'PENDING', -- PENDING, PUBLISHED, HIDDEN
up_count INT NOT NULL DEFAULT 0,
down_count INT NOT NULL DEFAULT 0,
helpful_score FLOAT NOT NULL DEFAULT 0.0, -- Computed Wilson score interval
created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
-- Index for fetching recency-sorted reviews efficiently
CREATE INDEX idx_reviews_recency
ON reviews (restaurant_id, status, review_id DESC);
-- Index for fetching helpfulness-sorted reviews efficiently
CREATE INDEX idx_reviews_helpfulness
ON reviews (restaurant_id, status, helpful_score DESC, review_id DESC);
CREATE TABLE review_media (
media_id VARCHAR(64) PRIMARY KEY,
review_id BIGINT REFERENCES reviews(review_id),
media_type VARCHAR(16) NOT NULL,
cdn_url TEXT NOT NULL,
status VARCHAR(16) NOT NULL DEFAULT 'UPLOADING' -- UPLOADING, READY, REJECTED
);
CREATE TABLE review_votes (
review_id BIGINT NOT NULL,
user_id BIGINT NOT NULL,
vote_value SMALLINT CHECK (vote_value IN (-1, 1)),
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (review_id, user_id)
);
CREATE TABLE restaurant_rating_stats (
restaurant_id BIGINT PRIMARY KEY,
review_count BIGINT NOT NULL DEFAULT 0,
rating_sum BIGINT NOT NULL DEFAULT 0,
count_1_star INT NOT NULL DEFAULT 0,
count_2_star INT NOT NULL DEFAULT 0,
count_3_star INT NOT NULL DEFAULT 0,
count_4_star INT NOT NULL DEFAULT 0,
count_5_star INT NOT NULL DEFAULT 0,
updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
);
4. Media Ingestion Pipeline
To prevent large data payloads from choking core API servers:
- Presigned Upload Link: The client requests a single-use presigned URL pointing directly to cloud object storage (e.g., AWS S3 bucket). The client uploads binary media directly to S3.
- Asynchronous Processing: An S3 object creation event fires a message to a queue consumed by background transcoders.
- Asset Sanitation & Encoding: The background worker:
- Scans assets for malware/NSFW content.
- Strips EXIF metadata (GPS coordinates, camera identifiers) for user privacy.
- Compresses images into WebP/AVIF formats and transcodes video into HLS streams.
- Publish Signal: Once assets are processed, the worker marks
review_media.status = 'READY'. The client displays placeholders until processing completes.
5. Scale & Performance Strategy
Keyset (Cursor) Pagination over Offset Pagination
Avoid OFFSET 1000 style queries because they execute $O(N)$ index scans and suffer from duplicate item skips when new reviews are inserted concurrently. Instead, use cursor pagination based on immutable keys:
Query for Most Recent Reviews:
SELECT * FROM reviews
WHERE restaurant_id = :restaurant_id
AND status = 'PUBLISHED'
AND review_id < :cursor_last_review_id
ORDER BY review_id DESC
LIMIT 20;
Query for Most Helpful Reviews:
SELECT * FROM reviews
WHERE restaurant_id = :restaurant_id
AND status = 'PUBLISHED'
AND (helpful_score, review_id) < (:cursor_score, :cursor_last_review_id)
ORDER BY helpful_score DESC, review_id DESC
LIMIT 20;
Hotspot Caching and Request Coalescing
Popular restaurants can experience massive read traffic spikes. We employ a multi-layered caching layout:
- Page-1 & Summary Cache: The overall rating summary and the first 2 pages of reviews for popular venues are cached in Redis under
rest:{id}:summaryandrest:{id}:reviews:recent:p1. - Single-Flight Lock (Request Coalescing): On a cache miss, application servers utilize distributed single-flight suppression to ensure only one DB query executes while concurrent requests await the populated cache response.
- Eventual Aggregation Pipeline:
- Review creations and votes write to the database transaction along with an Outbox Event.
- An Outbox Processor relays these events into an Apache Kafka topic.
- Background workers consume events in micro-batches to recalculate
restaurant_rating_statsand update Redis cached summaries, decoupling real-time writes from immediate read computation.