Data Model for Course Reviews, Aggregates, and Moderation
System DesignModel answerLast updated
Design an online course review system covering completion checks, transactional rating aggregates, edit histories, and keyset-paginated read paths.
Design the relational database architecture and query strategy for a course review and rating system within an online learning platform.
After completing a course, a learner can post a numerical score (1 to 5 stars) along with a text review. Potential students depend on overall course scores and review feeds when selecting courses to buy.
Focus on table structure, primary and foreign keys, integrity constraints, data mutations, and index design for high-volume read operations.
Requirements & Functional Expectations
- Completion Check: Only learners with a verified, completed course enrollment can write a review.
- Review Multiplicity Rules: A learner can submit at most one active review per completed enrollment. If a learner re-enrolls and completes the course again in the future, they can submit a new review for that specific completion instance.
- Lifecycle & Governance: Learners can edit or mark their reviews as deleted. Platform moderators can hide policy-violating reviews. Historical edit snapshots must be audit-logged.
- Read Access Paths:
- Course overview pages require real-time aggregated metrics (average rating, total counts, star distribution) without triggering expensive table scans.
- Review lists must support paginated browsing filtered to visible reviews, ordered by recency (newest first) or helpfulness (most upvotes first).
- Instructor Engagement: Instructors can publish at most one response per review written for their course.
Core Architecture Tasks
- Entities & Integrity Constraints: Define tables, unique keys, candidate keys, foreign key constraints, and custom checks (e.g., handling retakes, preventing duplicate reviews or orphaned responses).
- Read Path Optimizations & Indexing Strategy: Detail how aggregate ratings and sorted, paginated review feeds are served under heavy read throughput.
- Consistency Under State Mutations: Detail how review edits, deletions, upvotes, and moderation state changes keep aggregate counters and index structures accurate.
Hints
Hint 1
Key the review on the unique enrollment instance identifier rather than a composite (learner_id, course_id) key to seamlessly allow retake reviews.
Hint 2
Maintain real-time aggregated metrics in a dedicated aggregate table updated inside the write transaction to keep rating lookups O(1).
Hint 3
Implement keyset (cursor) pagination using composite indexes to prevent deep-OFFSET latency spikes on high-volume feeds.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
System Architecture & Storage Strategy
In an educational marketplace, read traffic to course landing pages dominates write traffic (review submissions and edits) by several orders of magnitude (e.g., $1000:1$). The core architectural goal is providing $O(1)$ rating summaries and index-backed $O(\text{page_size})$ review feed pagination while enforcing relational integrity during updates, edits, and moderation interventions.
Key Architectural Decisions:
- Enrollment-Anchored Reviews: Foreign keying
course_reviewstoenrollment_idnatively ensures that only enrolled learners review, while seamlessly supporting multiple reviews across sequential retakes. - Synchronous In-DB Aggregation: Course rating statistics (
rating_sum,review_count, individual star distribution) live in a dedicated summary row updated within the same transaction as the review write. - Composite Keyset Pagination: Keyset cursors eliminate offset-based performance degradation on courses with tens of thousands of submissions.
Part 1 — Relational Schema & Integrity Constraints
System Prerequisites
Assume base tables exist in the ecosystem:
CREATE TABLE learners (
learner_id BIGINT PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
CREATE TABLE courses (
course_id BIGINT PRIMARY KEY,
instructor_id BIGINT NOT NULL,
title VARCHAR(255) NOT NULL
);
CREATE TABLE enrollments (
enrollment_id BIGINT PRIMARY KEY,
learner_id BIGINT NOT NULL REFERENCES learners(learner_id),
course_id BIGINT NOT NULL REFERENCES courses(course_id),
completed_at TIMESTAMP WITH TIME ZONE NULL
);
1. Primary Review Entity (course_reviews)
CREATE TYPE review_visibility_status AS ENUM ('visible', 'pending_moderation', 'removed');
CREATE TABLE course_reviews (
review_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
enrollment_id BIGINT NOT NULL UNIQUE REFERENCES enrollments(enrollment_id),
course_id BIGINT NOT NULL REFERENCES courses(course_id),
learner_id BIGINT NOT NULL REFERENCES learners(learner_id),
rating SMALLINT NOT NULL CHECK (rating BETWEEN 1 AND 5),
headline VARCHAR(150),
body TEXT,
status review_visibility_status NOT NULL DEFAULT 'visible',
helpful_votes_count INT NOT NULL DEFAULT 0 CHECK (helpful_votes_count >= 0),
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
Key Integrity & Design Points:
UNIQUE (enrollment_id)Constraint: Automatically enforces at most one review per completed enrollment at the database level.- Denormalized
course_idandlearner_id: Derivable viaenrollment_id, but present directly oncourse_reviewsto eliminate multi-table joins during review feed reads and author lookups. - Completion Check Enforcement: Application transactions or DB triggers verify that
enrollments.completed_at IS NOT NULLbefore allowing insertion intocourse_reviews.
2. Review Audit Log (course_review_history)
To preserve regulatory compliance and moderation auditability, edits write snapshot rows rather than overwriting primary row attributes irreversibly:
CREATE TABLE course_review_history (
history_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
review_id BIGINT NOT NULL REFERENCES course_reviews(review_id) ON DELETE CASCADE,
rating SMALLINT NOT NULL CHECK (rating BETWEEN 1 AND 5),
headline VARCHAR(150),
body TEXT,
archived_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
3. Helpful Vote Tracking (review_helpfulness_votes)
Prevent duplicate votes per learner while maintaining accurate aggregate helpfulness metrics:
CREATE TABLE review_helpfulness_votes (
review_id BIGINT NOT NULL REFERENCES course_reviews(review_id) ON DELETE CASCADE,
learner_id BIGINT NOT NULL REFERENCES learners(learner_id),
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
PRIMARY KEY (review_id, learner_id)
);
4. Instructor Responses (instructor_review_responses)
CREATE TABLE instructor_review_responses (
response_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
review_id BIGINT NOT NULL UNIQUE REFERENCES course_reviews(review_id) ON DELETE CASCADE,
instructor_id BIGINT NOT NULL,
body TEXT NOT NULL,
created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW(),
updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT NOW()
);
Part 2 — High-Throughput Read Paths & Indexes
Read Path A: Instant Course Summary & Star Breakdown
Running aggregated functions (AVG, COUNT) live against millions of records per catalog view causes database lock contention and excessive I/O.
Design: Dedicated real-time counter table course_rating_aggregates.
CREATE TABLE course_rating_aggregates (
course_id BIGINT PRIMARY KEY REFERENCES courses(course_id),
review_count BIGINT NOT NULL DEFAULT 0 CHECK (review_count >= 0),
rating_sum BIGINT NOT NULL DEFAULT 0 CHECK (rating_sum >= 0),
count_star_1 BIGINT NOT NULL DEFAULT 0 CHECK (count_star_1 >= 0),
count_star_2 BIGINT NOT NULL DEFAULT 0 CHECK (count_star_2 >= 0),
count_star_3 BIGINT NOT NULL DEFAULT 0 CHECK (count_star_3 >= 0),
count_star_4 BIGINT NOT NULL DEFAULT 0 CHECK (count_star_4 >= 0),
count_star_5 BIGINT NOT NULL DEFAULT 0 CHECK (count_star_5 >= 0)
);
- Read Cost: $O(1)$ single-row primary key lookup.
- Computed Attributes: Average rating is calculated dynamically in code or view as
rating_sum / review_count.
Read Path B: Feed Paginated by Recency
SQL Query:
SELECT review_id, rating, headline, body, helpful_votes_count, created_at
FROM course_reviews
WHERE course_id = $1
AND status = 'visible'
AND (created_at, review_id) < ($2, $3) -- Cursor parameters
ORDER BY created_at DESC, review_id DESC
LIMIT 20;
Index Requirement:
CREATE INDEX idx_course_reviews_recency
ON course_reviews (course_id, status, created_at DESC, review_id DESC);
Read Path C: Feed Paginated by Helpfulness
SQL Query:
SELECT review_id, rating, headline, body, helpful_votes_count, created_at
FROM course_reviews
WHERE course_id = $1
AND status = 'visible'
AND (helpful_votes_count, review_id) < ($2, $3) -- Cursor parameters
ORDER BY helpful_votes_count DESC, review_id DESC
LIMIT 20;
Index Requirement:
CREATE INDEX idx_course_reviews_helpfulness
ON course_reviews (course_id, status, helpful_votes_count DESC, review_id DESC);
Part 3 — State Mutations & Aggregate Maintenance
1. Handling New Review Creation
Inserting a review requires updating aggregates within the same ACID transaction:
BEGIN;
-- 1. Create main review row
INSERT INTO course_reviews (enrollment_id, course_id, learner_id, rating, headline, body)
VALUES ($1, $2, $3, $4, $5, $6);
-- 2. Upsert course rating aggregates
INSERT INTO course_rating_aggregates (
course_id, review_count, rating_sum,
count_star_1, count_star_2, count_star_3, count_star_4, count_star_5
)
VALUES (
$2, 1, $4,
CASE WHEN $4 = 1 THEN 1 ELSE 0 END,
CASE WHEN $4 = 2 THEN 1 ELSE 0 END,
CASE WHEN $4 = 3 THEN 1 ELSE 0 END,
CASE WHEN $4 = 4 THEN 1 ELSE 0 END,
CASE WHEN $4 = 5 THEN 1 ELSE 0 END
)
ON CONFLICT (course_id) DO UPDATE SET
review_count = course_rating_aggregates.review_count + 1,
rating_sum = course_rating_aggregates.rating_sum + EXCLUDED.rating_sum,
count_star_1 = course_rating_aggregates.count_star_1 + EXCLUDED.count_star_1,
count_star_2 = course_rating_aggregates.count_star_2 + EXCLUDED.count_star_2,
count_star_3 = course_rating_aggregates.count_star_3 + EXCLUDED.count_star_3,
count_star_4 = course_rating_aggregates.count_star_4 + EXCLUDED.count_star_4,
count_star_5 = course_rating_aggregates.count_star_5 + EXCLUDED.count_star_5;
COMMIT;
2. Rating Modifications & Moderation Hiding
If a learner changes their star score (e.g., from 2 to 5 stars) or a moderator alters status from 'visible' to 'removed':
- Snapshot Old Version: Write the existing row state into
course_review_history. - Update Primary Record: Apply new text, rating, or status values in
course_reviews. - Adjust Aggregates:
- If rating changed: Subtract old rating from
rating_sum, add new rating torating_sum, adjust star count counters. - If status changed to
removedorpending_moderation: Subtract 1 fromreview_count, subtract old rating fromrating_sum, decrement corresponding star counter.
- If rating changed: Subtract old rating from
3. Voting Lifecycle Operations
When a learner upvotes a review:
BEGIN;
INSERT INTO review_helpfulness_votes (review_id, learner_id)
VALUES ($1, $2);
UPDATE course_reviews
SET helpful_votes_count = helpful_votes_count + 1
WHERE review_id = $1;
COMMIT;
If the learner has already voted on this review, the primary key constraint (review_id, learner_id) raises a unique violation, cleanly rolling back the transaction.
Trade-Offs & Complexity Evaluation
| Operational Metric | Choice / Implementation | Trade-Off Rationale |
|---|---|---|
| Integrity vs. Join Cost | Denormalized course_id on course_reviews | Takes additional storage space, but removes JOIN enrollments on hot review listing read paths. |
| Real-time Aggregation | Synchronous transactional aggregation table | Write path latency increases slightly (updating 2 tables instead of 1), but ensures immediate consistency and $O(1)$ landing page lookups. |
| Feed Pagination | Keyset / Cursor Pagination | Requires composite index support and binary cursor encoding on the client, but avoids $O(N)$ execution time of SQL OFFSET. |
| History Storage | Separate course_review_history table | Leaves the primary course_reviews table lean and fast for indexing while keeping a clean audit log. |