Skip to content

A platform for community discussion. Free, open, simple.

PERF: Speed up unread tracking for members with long topic history (#44582)

Alan Guo Xiang Tanc21ce17fd157
diff --git a/app/models/topic_user.rb b/app/models/topic_user.rb
index 8682f512f90..2b78b8e5703 100644
--- a/app/models/topic_user.rb
+++ b/app/models/topic_user.rb
@@ -568,4 +568,5 @@ end
# index_topic_users_on_topic_id_and_notification_level (topic_id,notification_level)
# index_topic_users_on_topic_id_and_user_id (topic_id,user_id) UNIQUE
# index_topic_users_on_user_id_and_topic_id (user_id,topic_id) UNIQUE
+# index_topic_users_on_user_id_and_topic_id_tracked (user_id,topic_id) WHERE (notification_level >= 2)
#
diff --git a/db/migrate/20261014065735_add_tracked_topic_users_index.rb b/db/migrate/20261014065735_add_tracked_topic_users_index.rb
new file mode 100644
index 00000000000..3e6b00a63a2
--- /dev/null
+++ b/db/migrate/20261014065735_add_tracked_topic_users_index.rb
@@ -0,0 +1,20 @@
+# frozen_string_literal: true
+
+class AddTrackedTopicUsersIndex < ActiveRecord::Migration[8.0]
+ disable_ddl_transaction!
+
+ INDEX_NAME = "index_topic_users_on_user_id_and_topic_id_tracked"
+
+ def up
+ remove_index :topic_users, name: INDEX_NAME, algorithm: :concurrently, if_exists: true
+ add_index :topic_users,
+ %i[user_id topic_id],
+ name: INDEX_NAME,
+ where: "notification_level >= 2",
+ algorithm: :concurrently
+ end
+
+ def down
+ remove_index :topic_users, name: INDEX_NAME, algorithm: :concurrently, if_exists: true
+ end
+end
diff --git a/db/structure.sql b/db/structure.sql
index 1ac359839ce..5f5ce93aa6c 100644
--- a/db/structure.sql
+++ b/db/structure.sql
@@ -24403,6 +24403,13 @@ CREATE UNIQUE INDEX index_topic_users_on_topic_id_and_user_id ON public.topic_us
CREATE UNIQUE INDEX index_topic_users_on_user_id_and_topic_id ON public.topic_users USING btree (user_id, topic_id);
+--
+-- Name: index_topic_users_on_user_id_and_topic_id_tracked; Type: INDEX; Schema: public; Owner: -
+--
+
+CREATE INDEX index_topic_users_on_user_id_and_topic_id_tracked ON public.topic_users USING btree (user_id, topic_id) WHERE (notification_level >= 2);
+
+
--
-- Name: index_topic_view_stats_on_topic_id_and_viewed_at; Type: INDEX; Schema: public; Owner: -
--
@@ -25913,6 +25920,7 @@ SET search_path TO "$user", public;
INSERT INTO "schema_migrations" (version) VALUES
('20261014145458'),
+('20261014065735'),
('20261013222431'),
('20261013183208'),
('20261013010026'),
diff --git a/lib/topic_query.rb b/lib/topic_query.rb
index da6da6caa8d..2c952c145a3 100644
--- a/lib/topic_query.rb
+++ b/lib/topic_query.rb
@@ -462,8 +462,7 @@ class TopicQuery
col_name = whisperer ? "highest_staff_post_number" : "highest_post_number"
list.where("tu.last_read_post_number < topics.#{col_name}").where(
- "COALESCE(tu.notification_level, :regular) >= :tracking",
- regular: TopicUser.notification_levels[:regular],
+ "tu.notification_level >= :tracking",
tracking: TopicUser.notification_levels[:tracking],
)
end