fix: Add composite index on messages for csat_metrics API performance (#11831)

This PR adds a composite index (:account_id, :content_type, :created_at)
on the table messages.

This index is added as a temporary fix for performance issues in the
CSAT responses controller where we query messages with account_id,
content_type and created_at. The current implementation
(account.message.input_csat.count) times out with millions of messages.

TODO: Create a dedicated csat_survey table and add entries when surveys
are sent, then query this table instead of the entire messages table for
better performance.
This commit is contained in:
Pranav
2025-06-27 15:48:04 -07:00
committed by GitHub
parent b7f3f72b9c
commit eea1ab3002
3 changed files with 23 additions and 1 deletions

View File

@@ -0,0 +1,20 @@
class AddIndexToMessages < ActiveRecord::Migration[7.0]
def change
# This index is added as a temporary fix for performance issues in the CSAT
# responses controller where we query messages with account_id, content_type
# and created_at. The current implementation (account.message.input_csat.count)
# times out with millions of messages.
#
# TODO: Create a dedicated csat_survey table and add entries when surveys are
# sent, then query this table instead of the entire messages table for better
# performance.
return if index_exists?(
:messages,
[:account_id, :content_type, :created_at],
name: 'idx_messages_account_content_created'
)
add_index :messages, [:account_id, :content_type, :created_at],
name: 'idx_messages_account_content_created', algorithm: :concurrently
end
end