feat: Database Query Optimization & API Latency Reduction - #348
Conversation
…s, lean execution, and pagination
…ponse compression
…ncy benchmark script
|
Important
This repository does not receive automatic reviews because it has fewer than 10 stars. ⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Strict review blocker: this branch conflicts with the base branch. Please rebase and resolve conflicts before requesting merge. |
2 similar comments
|
Strict review blocker: this branch conflicts with the base branch. Please rebase and resolve conflicts before requesting merge. |
|
Strict review blocker: this branch conflicts with the base branch. Please rebase and resolve conflicts before requesting merge. |
|
@zeemscript Gimme a few, lemme fix it and request for a proper review. |
|
@emarc99 this PR has merge conflicts with the |
On it! |
…audiobooks, and latency optimizations
PR Description
📌 Context & Problem Statement
The backend API was experiencing high latency on read-heavy endpoints (
/api/courses,/api/books,/api/users), impacting the user experience on the frontend dashboard and content pages.Root cause analysis identified the following bottlenecks:
status,createdBy,author,categoryRef,recipient) caused full collection scans in MongoDB.sections(lessons) and bookreviews.🚀 Key Improvements
1. Database Schema Indexing Strategy
Added targeted single-field and compound indexes to optimize filter and sort paths:
Course: Added compound index{ status: 1, createdAt: -1 }(published listing),{ categoryRef: 1, status: 1 }(category filtering),{ createdBy: 1 }(creator dashboard), and{ enrolledUsers: 1 }(user enrollment count).Book: Added indexes on{ author: 1 },{ category: 1 }, and{ createdAt: -1 }.User: Added indexes on{ role: 1 }and{ verifiedEducator: 1 }.Space: Added indexes on{ host: 1 }and compound index{ status: 1, eventDate: 1 }.Notification: Added compound index{ recipient: 1, isDeleted: 1, createdAt: -1 }.2. Selective Field Projections &
.lean()Query ExecutiongetCourses,getBooks) now select only light summary fields (_id,title,description,category,price,currency,thumbnail/image,rating,numReviews,createdBy/author,createdAt). Heavy nested arrays (sections,reviews,enrolledUsers) are excluded from list views and fetched only on detail endpoints..lean()across all read controllers (courseController,bookController,userController) to bypass Mongoose document hydration overhead..populate("createdBy", "name email avatar")).3. Pagination Support
pageandlimitquery parameters ongetCoursesandgetBooks.{ "success": true, "page": 1, "limit": 20, "total": 500, "hasMore": true, "courses": [...] }4. Connection Pooling & Compression Middleware
maxPoolSize: 50(configurable viaprocess.env.MAX_POOL_SIZE),minPoolSize: 10, andmaxIdleTimeMS: 30000insrc/config/db.js.compressionmiddleware withthreshold: 1024and compression level 6 inapp.js.📊 Empirical Benchmark Results
Benchmarked against 500 course and 500 book documents over 50 test iterations (
node scripts/benchmark.js):GET /api/courses)GET /api/books)All target endpoints now respond well below the 200ms acceptance criteria under normal load.
🧪 Verification & Test Results
npm testacross all suites:📦 Commit History
fc381c0perf(db): add database indexes to Course, Book, User, Space, and Notification schemas3e1f872perf(api): optimize list and detail queries with selective projections, lean execution, and pagination6f3681bperf(config): tune MongoDB connection pool settings and configure response compression43eed18test(perf): update Jest configuration, test setup, and add query latency benchmark script🔗 Related Issue
Closes #1