Files
back_end_oudelaa/docs/PERFORMANCE_IMPROVEMENTS.md

7.1 KiB

Performance improvements — 2026-11-07

Implemented and measured against the code at commit d936446. Measurements ran locally on Node v24.16.0 and an Intel i7-13650HX, using a private MongoDB process, 60 synthetic users and 6000 text posts. No application database, real account or external service was used. Redis was disabled; cached requests used the bounded local fallback.

Changes

  • Personalized feed diversity precomputes author/type/hashtag metadata and selects only the prefix needed for the requested page. It preserves the previous IDs, tie order, adjusted scores and total count. Full and partial outputs are compared against a frozen copy of the previous algorithm, including mixed-case and duplicate hashtags.
  • feed_trending_order_v1 matches the complete Trending order, including _id as a deterministic tie breaker. feed_popular_order_v1 matches popular-candidate ordering. Both indexes are additive; existing indexes remain intact.
  • Trending returns a validated trending-v1 keyset cursor. Subsequent requests seek from the counter/date/ID boundary and use no offset skip. A redundant leading range bound prevents MongoDB from scanning the earlier portion of the compound sort index. Legacy numeric/offset cursors and explicit page numbers remain supported.
  • Trending reads one lookahead row to determine whether another page exists. Deleting earlier posts cannot prematurely end pagination because the historical offset exceeds the new total. Tests cover tied sort values and insertion/deletion ahead of a boundary.
  • The local cache has LRU eviction for ordinary values, configurable entry/serialized-byte budgets, and a 30-second expiry sweep for values and leases. Shutdown clears the timer. Active counters and NX reservations are protected from eviction; exhausting their capacity returns 503 rather than resetting rate limits or admitting duplicate work. Local counter windows now expire from the first increment, matching Redis behavior.

HTTP measurements

The reference build was rebuilt separately from d936446 and benchmarked before the final workspace build using the same harness. Each workload ran for 5 seconds after 5 sequential warmup requests, with concurrency 8. Every recorded request succeeded; the harness aborts on HTTP errors or timeouts. Response bodies are fully consumed before latency is recorded.

Workload Before req/s After req/s Before p95 ms After p95 ms
Uncached personalized feed 2.72 7.59 2973.59 1114.57
Trending first page 42.56 54.87 226.27 173.52
Trending next cursor 42.38 47.61 231.93 199.73
Cached personalized feed 415.43 394.07 30.90 36.37
Compatibility search 47.78 41.12 195.41 241.76
Health 1678.96 1975.61 9.59 6.70

The uncached-feed observation is approximately 2.79x throughput and 62.5% lower p95 latency in this comparison. Cached-feed and search throughput did not improve in the final runs; search code was not changed. Earlier runs differed materially even for the unchanged health endpoint. These short samples, especially the reference uncached feed's 16 requests, are exploratory measurements rather than production capacity or statistically established gains. The uncached feed still needs further work before claiming low latency under sustained load.

Raw results: reference repeat, final workspace, initial reference. UTC timestamps are retained in the raw files; the report date uses Asia/Riyadh.

Database and CPU evidence

Check Before After
Documents examined to return 20 Trending posts 6000 20
Blocking sort for the first Trending page Yes No
Documents examined after position 4000, same final index 4020 with skip 65 with keyset
Diversity median, 400 candidates / first 20 results 10.108 ms 0.491 ms
Diversity median, 1000 candidates / first 20 results 77.805 ms 1.147 ms

The CPU comparison runs both implementations in one process, with 10 warmups and 50 measurements each. The old implementation computes all ranks; the new implementation computes the exact prefix consumed by the page. This is not a full HTTP measurement. Full-output timings are also recorded in ranking results. The isolated database harness checks that deep keyset pagination examines fewer index keys than skip, and verifies page contents with equal ranks and mutations ahead of the cursor. Database-only verification records the same plan.

Keyset cursors describe live engagement ranks, not a frozen snapshot. Updates to the ranked counters can move posts across a boundary. The keyset optimization benefits requests using the returned cursor; legacy offsets still incur skip work. Personalized feed work grows with the requested prefix, up to the existing 1000-candidate ceiling. Added indexes consume storage and add work to counter updates; write throughput was not benchmarked here.

Reproduce

Requirements: repository dependencies installed, mongod on PATH (or MONGOD_BINARY set explicitly), and a current build. Benchmark connections and test JWTs are created inside the harness; it never takes a database URI from .env.

npm run build
npm run perf:isolated -- --output local-performance.json
npm run perf:isolated -- --database-only --output local-database-plans.json
npm run perf:ranking -- --output local-ranking.json

--build-dir <path-to-dist> benchmarks a separately compiled reference build with the same harness. The temporary comparison source tree used for this review is not required for normal benchmarks. Each MongoDB process is stopped in finally; temporary database files are left under the operating-system temp directory for diagnostics.

Validation completed: full TypeScript build and ESLint; affected controller/repository, ranking, cursor and cache tests; 21 isolated end-to-end tests; and 5 load-tool tests. Affected tests were rerun after the final pagination/cache changes. Database-plan and tie/mutation checks ran against real MongoDB, not repository mocks.

Deployment settings

Production disables automatic index creation by default. Build the code and add the declared feed indexes to the intended database before deploying (the later two-stage feed iteration also adds feed_recent_order_v1):

npm run db:feed-indexes -- --dry-run
# Set MONGODB_URI explicitly in the deployment environment, then:
npm run db:feed-indexes

The command deliberately does not load .env, never drops existing indexes, and is safe to rerun for these named index definitions. It was dry-run locally; the application database was not modified.

Local fallback defaults are documented in .env.example:

CACHE_MEMORY_MAX_ENTRIES=10000
CACHE_MEMORY_MAX_BYTES=67108864

The byte budget covers serialized keys and values; JavaScript object overhead is additional. Redis retains its existing behavior and remains the shared cache/counter backend for multiple application replicas. The actual .env was not changed.