Skip to content

refactor: optimize MongoDB queries in findMentionedMessages and findStarredMessages with Promise.all#39607

Open
CodeUltr0n wants to merge 6 commits into
RocketChat:developfrom
CodeUltr0n:perf/optimize-messages-db-queries
Open

refactor: optimize MongoDB queries in findMentionedMessages and findStarredMessages with Promise.all#39607
CodeUltr0n wants to merge 6 commits into
RocketChat:developfrom
CodeUltr0n:perf/optimize-messages-db-queries

Conversation

@CodeUltr0n
Copy link
Copy Markdown

@CodeUltr0n CodeUltr0n commented Mar 13, 2026

Proposed changes

Optimizes MongoDB query performance in two Activity Hub-related service functions by replacing sequential database lookups with concurrent Promise.all calls.

Affected Functions

File: apps/meteor/app/api/server/lib/messages.ts

  1. findMentionedMessages (lines 7–44)
  2. findStarredMessages (lines 46–83)

The Problem

Both functions were performing two independent MongoDB queries sequentially, even though neither result depends on the other:

// Before — sequential (slower)
const room = await Rooms.findOneById(roomId);
const user = await Users.findOneById(uid, { projection: { username: 1 } });

// After — concurrent (faster)
const [room, user] = await Promise.all([
  Rooms.findOneById(roomId),
  Users.findOneById<Pick<IUser, 'username'>>(uid, { projection: { username: 1 } }),
]);

Performance Impact

For a typical deployment with 50ms DB latency:

  • Before: ~100ms (50ms + 50ms sequential)
  • After: ~50ms (both run simultaneously)
  • Result: ~50% faster response time for mentions and starred messages endpoints

Issue(s)

Related to Activity Hub project (#39577). Closes #39606.

This optimizes the backend service functions used by:

  • GET /v1/chat.getMentionedMessages
  • GET /v1/chat.getStarredMessages

These endpoints power the Mentions and Starred Messages tabs in the Activity Hub UI.


Steps to test or reproduce

  1. Open any room's Mentions panel or Starred Messages panel
  2. Observe faster panel load times (reduced API response time)
  3. Confirm no visual or behavioral changes

Performance improvement can be verified via:

  • Server-side query timing logs
  • Network tab showing faster API response times

Further comments

Summary by CodeRabbit

  • Refactor
    • Performance improvements across chat: thread listing, synchronization, message retrieval, and search (including mentions and starred messages) now fetch related data in parallel, yielding faster response times and snappier UI behavior.

@CodeUltr0n CodeUltr0n requested review from a team as code owners March 13, 2026 17:27
@dionisio-bot
Copy link
Copy Markdown
Contributor

dionisio-bot Bot commented Mar 13, 2026

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is missing the 'stat: QA assured' label
  • This PR is missing the required milestone or project

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@changeset-bot
Copy link
Copy Markdown

changeset-bot Bot commented Mar 13, 2026

🦋 Changeset detected

Latest commit: 2383357

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 41 packages
Name Type
@rocket.chat/meteor Patch
@rocket.chat/core-typings Patch
@rocket.chat/rest-typings Patch
@rocket.chat/uikit-playground Patch
@rocket.chat/api-client Patch
@rocket.chat/apps Patch
@rocket.chat/core-services Patch
@rocket.chat/cron Patch
@rocket.chat/ddp-client Patch
@rocket.chat/fuselage-ui-kit Patch
@rocket.chat/gazzodown Patch
@rocket.chat/http-router Patch
@rocket.chat/livechat Patch
@rocket.chat/model-typings Patch
@rocket.chat/ui-avatar Patch
@rocket.chat/ui-client Patch
@rocket.chat/ui-contexts Patch
@rocket.chat/ui-voip Patch
@rocket.chat/web-ui-registration Patch
@rocket.chat/account-service Patch
@rocket.chat/authorization-service Patch
@rocket.chat/ddp-streamer Patch
@rocket.chat/omnichannel-transcript Patch
@rocket.chat/presence-service Patch
@rocket.chat/queue-worker Patch
@rocket.chat/abac Patch
@rocket.chat/federation-matrix Patch
@rocket.chat/license Patch
@rocket.chat/media-calls Patch
@rocket.chat/omnichannel-services Patch
@rocket.chat/pdf-worker Patch
@rocket.chat/presence Patch
rocketchat-services Patch
@rocket.chat/models Patch
@rocket.chat/network-broker Patch
@rocket.chat/omni-core-ee Patch
@rocket.chat/mock-providers Patch
@rocket.chat/ui-video-conf Patch
@rocket.chat/instance-status Patch
@rocket.chat/omni-core Patch
@rocket.chat/server-fetch Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Mar 13, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c47d4582-e890-4a38-8792-df7cae918e8e

📥 Commits

Reviewing files that changed from the base of the PR and between 5c323c2 and 2383357.

📒 Files selected for processing (1)
  • .changeset/perf-thread-endpoints-promise-all.md
🚧 Files skipped from review as they are similar to previous changes (1)
  • .changeset/perf-thread-endpoints-promise-all.md

Walkthrough

Replaces sequential awaits for independent room and user lookups with concurrent Promise.all calls across message and chat thread endpoints; adds a changeset entry and removes a stray TODO comment.

Changes

Cohort / File(s) Summary
Promise.all optimization — message endpoints
apps/meteor/app/api/server/lib/messages.ts
Parallelized Rooms.findOneById and Users.findOneById with Promise.all in findMentionedMessages and findStarredMessages (removed sequential user fetch).
Promise.all optimization — chat endpoints
apps/meteor/app/api/server/v1/chat.ts
Replaced sequential awaits with Promise.all for user and room lookups across chat.getThreadsList, chat.syncThreadsList, chat.getThreadMessages, and chat.syncThreadMessages.
Changelog / minor cleanup
.changeset/perf-thread-endpoints-promise-all.md, apps/meteor/client/views/room/contextualBar/Info/RoomInfo/ABAC/RoomInfoABACSection.tsx
Added changeset documenting the optimization; removed a TODO comment in RoomInfoABACSection (no runtime/API changes).

Sequence Diagram(s)

mermaid
sequenceDiagram
participant Client
participant Server
participant DB
Client->>Server: Request (mentions / starred / threads)
Server->>DB: Rooms.findOneById(roomId)
Server->>DB: Users.findOneById(uid, {username})
Note right of DB: Both queries run concurrently via Promise.all
DB-->>Server: room, user
Server->>Server: validate room access & user existence
Server-->>Client: Response (messages)

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Out of Scope Changes check ❓ Inconclusive Most changes align with the optimization scope, but the PR includes unrelated modifications: thread endpoints in chat.ts and TODO comment removal in RoomInfoABACSection.tsx appear outside issue #39606's stated scope. Clarify whether chat.ts thread endpoint optimizations and RoomInfoABACSection.tsx changes are part of a related performance initiative or should be split into separate PRs.
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: optimizing MongoDB queries in two specific functions using Promise.all for concurrent execution.
Linked Issues check ✅ Passed The PR fully addresses all coding requirements from issue #39606: both findMentionedMessages and findStarredMessages now use Promise.all to concurrently fetch room and user data.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

📝 Coding Plan
  • Generate coding plan for human review comments

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 4 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name=".changeset/perf-thread-endpoints-promise-all.md">

<violation number="1" location=".changeset/perf-thread-endpoints-promise-all.md:5">
P2: Changeset description is inconsistent with the PR’s actual scope, so release notes would report the wrong endpoints being optimized.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

'@rocket.chat/meteor': patch
---

Improve performance of thread-related chat endpoints by replacing sequential `await` calls with concurrent `Promise.all` for independent `Users` and `Rooms` database lookups. Affected endpoints: `chat.getThreadsList`, `chat.syncThreadsList`, `chat.getThreadMessages`, `chat.syncThreadMessages`.
Copy link
Copy Markdown
Contributor

@cubic-dev-ai cubic-dev-ai Bot Mar 13, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Changeset description is inconsistent with the PR’s actual scope, so release notes would report the wrong endpoints being optimized.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At .changeset/perf-thread-endpoints-promise-all.md, line 5:

<comment>Changeset description is inconsistent with the PR’s actual scope, so release notes would report the wrong endpoints being optimized.</comment>

<file context>
@@ -0,0 +1,5 @@
+'@rocket.chat/meteor': patch
+---
+
+Improve performance of thread-related chat endpoints by replacing sequential `await` calls with concurrent `Promise.all` for independent `Users` and `Rooms` database lookups. Affected endpoints: `chat.getThreadsList`, `chat.syncThreadsList`, `chat.getThreadMessages`, `chat.syncThreadMessages`.
</file context>
Fix with Cubic

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

perf: Optimize MongoDB queries in findMentionedMessages and findStarredMessages with Promise.all

1 participant