Build a Restaurant and Dish Rating Service End to End
System DesignModel answerLast updated
Design a backend for browsing eateries, posting star ratings and written reviews, and keeping aggregates, search, and moderation trustworthy at scale.
Build a Restaurant and Dish Rating Service
You are asked to design the backend for a service where people find places to eat, read what others wrote, and publish their own star ratings and written reviews.
Begin by pinning down scope. Decide whether reviews target restaurants only, individual dishes, or both, and state whether ordering and delivery are handled by a different system.
Part 1: Product and data contract
Describe the core records: users, businesses, dishes (if in scope), reviews, ratings, photos, and moderation status. Give the read and write APIs. State your policy on whether a user can review the same entity more than once, and how edits and removals change the displayed totals.
Cover:
- Stable identifiers for entities and reviews.
- Rating scale, review lifecycle, and duplicate-review rule.
- Idempotent creation and versioned edits.
- Who can see or change what: authors, business owners, moderators, anonymous readers.
Part 2: Discovery and review reads
Design lookup for businesses or dishes, nearby and text search if needed, review listing with pagination and sorting, rating summaries, photo display, caching, and what a user sees right after posting.
Cover:
- Authoritative records versus derived search and aggregate views.
- Cursor pagination that stays stable, with a deterministic tie-breaker.
- Maintaining rating count and sum through edits and removals.
- Stated freshness expectations for search results, summaries, and detail pages.
Part 3: Abuse, trust, and privacy
Explain how you handle spam, harassment, fake reviews, owner disputes, user reports, automated detection, human moderation, appeals, and personal data.
Cover:
- Moderation states that are distinct from hard deletion.
- Behavioral signals (rate, account age, relationships) treated as evidence, not proof.
- Evidence retention, appeal history, and auditable decisions.
- Protection of personal data and sensitive location data.
Part 4: Scale and operations
Discuss partitioning, very popular businesses, read and write amplification, search-index lag, media delivery, retries, reconciliation, and monitoring.
Cover:
- Partitioning that avoids a single global lock on reviews.
- Idempotent change events and projections that can be rebuilt.
- CDN-served media with safe upload handling.
- Metrics for freshness, aggregate drift, abuse, and user-perceived latency.
Hints
Hint 1
Settle review identity first: choose a uniqueness rule such as one active review per (user, entity), and make creation idempotent with a client-supplied key so retries never double count.
Hint 2
Treat the review table as the single source of truth and everything else (search index, rating summary, caches) as a projection fed by an ordered, idempotent event stream that can be replayed.
Hint 3
Keep moderation as a state machine (pending, published, hidden, removed, appealed) rather than deleting rows, and have aggregates react to state transitions, not just to creates.
Hint 4
For hot businesses, shard reviews by entity but accumulate aggregate deltas in batches or per-shard counters so one popular place does not become a write hotspot.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Scope and assumptions
I would scope v1 to reviews on businesses and dishes, with ordering and delivery out of scope (a separate system may link in). Reviews carry a 1-5 integer star rating, optional text, and up to a few photos. Dish reviews are optional and attach to a dish belonging to a business.
Rough scale for sizing: 50M MAU, 5M new reviews per day (~60 writes/s average, ~500/s peak), and a read-to-write ratio near 200:1, so ~10-20k reads/s at peak. Reads dominate, which shapes the whole design.
Part 1: Data contract
Entities
User(id, handle, created_at, trust_signals)Business(id, name, geo, category, owner_id?, status)Dish(id, business_id, name)Review(id, author_id, target_type, target_id, rating, body, version, state, created_at, updated_at, idempotency_key)Photo(id, review_id, object_key, scan_status)ModerationCase,ModerationAction,Appeal(append-only audit records)
IDs are opaque, time-sortable (ULID or snowflake style), never reused.
Duplicate policy: one active review per (author_id, target_type, target_id), enforced by a unique index. A second submission is treated as an edit, or rejected with a pointer to the existing review. Optionally allow an "update after revisit" that keeps history but counts only the latest rating.
APIs
POST /reviewswith anIdempotency-Keyheader. Same key and payload returns the original result; same key with a different payload returns 409.PATCH /reviews/{id}withIf-Match: versionfor optimistic concurrency. A stale version returns 412.DELETE /reviews/{id}is author withdrawal, a soft delete.GET /businesses/{id},GET /businesses/{id}/reviews?cursor=&sort=,GET /search?q=&lat=&lng=.
Visibility
- Readers see only
publishedreviews. - Authors also see their own pending or hidden reviews and the reason.
- Owners can post a public reply and flag or report, but cannot edit or hide reviews.
- Moderators see everything plus the audit trail.
Part 2: Reads and aggregates
Primary store: a sharded relational or wide-column store keyed by target_id, holding reviews. Secondary derived views:
- Search index (Elasticsearch/OpenSearch) with geo and text fields, populated from change events. Freshness target: seconds to a minute. A new business may take longer to appear; that is acceptable.
- Rating summary per target:
count,sum, and a histogram of 1-5 buckets. Average issum / count, computed at read time. - Cache (Redis plus CDN for public pages) for hot detail pages and first review pages.
Aggregate maintenance: every state change emits a delta. Create adds +1 to the bucket. Edit changes the bucket from old to new. Hide, remove, or restore moves the review out of or into the published set. Because deltas are derived from (old_state, old_rating) and (new_state, new_rating) on the same row, a single transition function handles all cases. Consumers dedupe by (review_id, version) so replays are harmless.
Pagination: use keyset cursors, never offsets. For "newest": order by (created_at DESC, id DESC); the cursor encodes both. For "highest rated" or "most helpful": order by (score DESC, id DESC). The tie-breaker id makes ordering deterministic when many rows share a timestamp or score. Sorting by helpfulness uses a periodically updated score, so the cursor should carry the score snapshot to avoid items jumping between pages.
After posting: the author gets read-your-writes by reading from the primary (or by merging their just-created review into the first page client-side or via a short-lived per-user overlay). Other users see the review once the cache TTL or invalidation event passes, typically within a few seconds. Summaries are eventually consistent; I would state this explicitly (for example, under 10 s at p99).
Part 3: Moderation, trust, privacy
State machine: pending -> published -> hidden -> removed, with appealed branching back to published or confirming removal. Rows are never destroyed by moderation; only legal erasure requests purge content, and even then audit metadata (without personal text) remains.
Detection pipeline:
- Synchronous cheap checks: rate limits per account and IP, banned terms, duplicate text hashes.
- Asynchronous scoring: text classifier for toxicity or spam, burst detection (many five-star reviews for one business in an hour), account age, device or network clustering, and relationship signals such as reviewer and owner sharing payment or contact data.
- These are signals, not verdicts. A high score routes to human review or delays publication; it does not by itself ban a user, because legitimate events (a viral post, a promotion) look similar to coordinated fraud.
Disputes and appeals: owners can report with a reason; the reviewer is notified and can supply evidence (receipt, photo). Every decision writes an immutable ModerationAction with actor, rule, evidence references, and timestamp. Appeals are reviewed by a different moderator when possible.
Privacy: minimise stored personal data, hide exact reviewer identity from owners, strip EXIF (including GPS) from photos, avoid exposing a reviewer's home-area patterns, encrypt at rest, restrict moderator access by role with access logging, and support export and deletion requests.
Part 4: Scale and operations
Partitioning: shard reviews by target_id so reads for a business are local and the unique (author, target) constraint is enforced within one shard. There is no global lock; contention exists only per business.
Hot businesses: a viral restaurant gets many writes and reads. Mitigations: cache the summary and first pages aggressively with request coalescing, serve stale-while-revalidate, and apply aggregate deltas through per-shard counters or micro-batches (for instance flush every second) rather than a row update per review.
Event flow: write to the primary and an outbox table in one transaction; a relay publishes to Kafka. Consumers (search indexer, aggregator, cache invalidator, notification, abuse scoring) are idempotent and keyed by target_id to preserve per-entity order.
Reconciliation: nightly or continuous jobs recompute counts and sums from the source of truth for sampled or all targets, compare them with the stored summary, and repair drift. Search indexes can be rebuilt from a snapshot plus event replay.
Media: clients upload directly to object storage via pre-signed URLs, into a quarantine bucket. A worker verifies type and size, scans for malware and disallowed content, strips metadata, generates resized variants, then promotes to the public bucket behind a CDN. The review shows photos only after scan_status = clean.
Metrics:
- Freshness: event-to-index lag, event-to-summary lag.
- Correctness: aggregate drift rate found by reconciliation.
- Abuse: reports per 1k reviews, auto-flag precision, moderation queue age, appeal overturn rate.
- UX: p50/p99 latency for search, detail page, and post; cache hit rate; error rate.
Trade-offs and common mistakes
- Using offset pagination or sorting only by timestamp, causing duplicates and skips.
- Storing only an average, which cannot be corrected on edits; keep count, sum, and histogram.
- Hard-deleting moderated content, losing auditability and breaking appeals.
- Treating fraud signals as proof and auto-banning.
- Updating a single aggregate row synchronously for every review on a hot business.
- Forgetting idempotency, so client retries double count.
- Leaving EXIF location data in uploaded photos.
A reasonable deliberate trade-off is accepting seconds of staleness in search and summaries in exchange for a simpler, cheaper, highly available read path, while keeping the review write itself strongly consistent within its shard.