perf: add composite index for account-scoped conversation created_at sort (#15360)

## Description

Adds a composite index `(account_id, status, created_at)` on
`conversations`.

Sorting an account's conversation list by `created_at` ("newest first")
across all inboxes has no supporting index today, so Postgres falls back
to a backward scan of the global `index_conversations_on_created_at`
filtered by `account_id`. On large databases the planner estimates a
very deep scan and the query can exceed the statement timeout. The
composite index lets the ordered limit be served directly from the
`account_id`/`status` prefix. The default `last_activity_at` sort and
inbox-filtered views are unaffected (already indexed).

The index is created with `algorithm: :concurrently` (no table lock). On
very large installations, create it out-of-band concurrently before
deploying so the migration doesn't run a long build.

Fixes https://linear.app/chatwoot/issue/CW-7888

## Type of change

- [x] Bug fix (non-breaking change which fixes an issue)
This commit is contained in:
Vishnu Narayanan
2026-08-13 18:34:12 +05:30
committed by GitHub
parent 40f5381da6
commit fefa0a6966
2 changed files with 14 additions and 1 deletions

View File

@@ -0,0 +1,12 @@
class AddAccountStatusCreatedAtIndexToConversations < ActiveRecord::Migration[7.1]
disable_ddl_transaction!
def change
# Serves account-scoped conversation lists sorted by created_at (e.g. "newest first"),
# which otherwise fall back to a backward scan of the global created_at index.
add_index :conversations, [:account_id, :status, :created_at],
name: 'index_conversations_on_account_id_status_created_at',
algorithm: :concurrently,
if_not_exists: true
end
end

View File

@@ -10,7 +10,7 @@
#
# It's strongly recommended that you check this file into your version control system.
ActiveRecord::Schema[7.1].define(version: 2026_08_06_000000) do
ActiveRecord::Schema[7.1].define(version: 2026_08_07_101420) do
# These extensions should be enabled to support this database
enable_extension "pg_stat_statements"
enable_extension "pg_trgm"
@@ -854,6 +854,7 @@ ActiveRecord::Schema[7.1].define(version: 2026_08_06_000000) do
t.index ["account_id", "display_id"], name: "index_conversations_on_account_id_and_display_id", unique: true
t.index ["account_id", "id"], name: "index_conversations_on_id_and_account_id"
t.index ["account_id", "inbox_id", "status", "assignee_id"], name: "conv_acid_inbid_stat_asgnid_idx"
t.index ["account_id", "status", "created_at"], name: "index_conversations_on_account_id_status_created_at"
t.index ["account_id"], name: "index_conversations_on_account_id"
t.index ["assignee_id", "account_id"], name: "index_conversations_on_assignee_id_and_account_id"
t.index ["campaign_id"], name: "index_conversations_on_campaign_id"