discourse/plugins/chat/app/queries/chat
Sam 83bed592e2
PERF: speed up chat channel and thread unread queries (#39398)
Rewrites the channel and thread unread queries to use a CTE that
picks the candidate set up front, followed by LATERAL subqueries
for each aggregate. The previous form used three correlated
subqueries that each re-joined the user's full membership lists,
and packed the unread predicate into a single OR-bag that forced
a sequential scan over every message past last_read_message_id.

The channel query now:
- Limits candidate channels in a CTE before aggregating.
- Splits unread_count into three additive, index-friendly pieces
  (standalone messages, thread original messages, and DM thread
  replies) instead of one OR branch.
- Pushes the muted check into a CASE on the outer row.

The thread query now:
- Orders candidate memberships by last_message_id and caps them
  at MAX_THREADS in the CTE, so recent threads always win.
- Derives unread and watched counts from a single aggregate
  switched by notification_level.
- Skips threads whose channel membership is missing.

Also adds a covering index on chat_messages(thread_id, id) INCLUDE
(user_id) WHERE deleted_at IS NULL to support the thread aggregates
as index-only scans, and adds specs for the orphaned-thread case
and the MAX_THREADS recency cap.

---

This gives this about 50x perf improvement in testing

---------

Co-authored-by: Martin Brennan <martin@discourse.org>
2026-04-22 14:57:56 +10:00
..
channel_memberships_query.rb PERF: auto join & leave chat channels (#29193) 2024-11-12 15:00:59 +11:00
channel_unreads_query.rb PERF: speed up chat channel and thread unread queries (#39398) 2026-04-22 14:57:56 +10:00
messages_query.rb DEV: Apply consistent N+1 fix pattern to ThreadOriginalMessageSerializer (#38667) 2026-03-17 14:17:58 -05:00
thread_participant_query.rb FIX: handle thread participants limit on the frontend (#23839) 2023-10-09 14:04:59 +08:00
thread_unreads_query.rb PERF: speed up chat channel and thread unread queries (#39398) 2026-04-22 14:57:56 +10:00
tracking_state_report_query.rb FEATURE: Add ability to watch chat threads (#28639) 2024-09-02 16:45:55 +04:00
users_from_usernames_and_groups_query.rb SECURITY: respect allow private messages prefernce for DMs 2025-03-26 09:26:36 +08:00