perf: Severe N+1 query loop and high view latency in _conversation.json.jbuilder (350+ queries per page of 25 conversations)
Describe the bug / Performance Issue
When fetching the conversation list (GET /api/v1/accounts/:account_id/conversations), rendering a single page of 25 conversations issues between 250 and 363 SQL queries (an average of ~14 queries per conversation).
On instances with active traffic or a moderately large messages table, this causes severe view rendering bottlenecks (often spending 1.5s to 4.0s+ inside Jbuilder alone), blocks Puma worker threads, and exhausts the database connection pool during concurrent requests.
Production Trace / Benchmark
From Rails production logs during a standard paginated conversation list request (page=1, 25 conversations):
Completed 200 OK in 7022ms (Views: 4089.4ms | ActiveRecord: 2746.9ms (363 queries, 173 cached))Even after indexing messages (conversation_id, created_at DESC) which brought database execution time down to ~340ms, the request still spends nearly 1.5 seconds in Ruby/Jbuilder just executing and collecting the 363 query roundtrips:
Completed 200 OK in 1854ms (Views: 1486.4ms | ActiveRecord: 343.0ms (363 queries, 174 cached))Root Cause Analysis: Hotspots in _conversation.json.jbuilder
Tracing app/views/api/v1/conversations/partials/_conversation.json.jbuilder reveals multiple per-conversation queries executed inside the collection loop:
unread_countviaconversation.unread_incoming_messages.count(Line 63):# app/models/conversation.rb:202 def unread_incoming_messages unread_messages.where(account_id: account_id).incoming.last(10) endCalling
.last(10)on the relation generatesSELECT ... FROM messages WHERE conversation_id = ? ... ORDER BY id DESC LIMIT 10per conversation. For 25 conversations, this generates 25 separate queries tomessages.last_non_activity_message(Line 64):json.last_non_activity_message conversation.messages.where(account_id: conversation.account_id).non_activity_messages.first.try(:push_event_data)Executes
SELECT ... FROM messages WHERE conversation_id = ? AND message_type != 2 ORDER BY created_at DESC LIMIT 1per conversation (another 25 queries).last_messagelookup with blob attachments (Lines 36-39):last_message = conversation.messages.where(account_id: conversation.account_id) .includes([{ attachments: [{ file_attachment: [:blob] }] }]) .reorder(created_at: :desc, id: :desc).firstIssues queries for messages, active storage attachments, and blobs for each conversation.
Sender, Assignee, and Contact Inbox associations (Lines 5-27):
conversation.contact_inbox&.hmac_verifiedqueriescontact_inboxes.- Contact and agent partials look up
avatar_attachment => blob.
Because ConversationFinder does not pre-load or batch these associations, 25 items incur approximately $25 \times 14 = 350+$ database roundtrips.
Proposed Solutions
- Eager Loading in
ConversationFinder: Pre-loadcontact_inbox,contact => { avatar_attachment: :blob },assigned_entity => { avatar_attachment: :blob }, andteaminconversations_base_query. - Denormalize or Batch Previews:
- Pre-load the latest non-activity and latest message IDs in a single batch query (e.g. using
DISTINCT ON (conversation_id)or a window function) instead of 50 individual queries per page. - Or store
last_activity_message_idon theconversationsrecord during message creation.
- Pre-load the latest non-activity and latest message IDs in a single batch query (e.g. using
- Optimize
unread_incoming_messages: Batch calculate unread counts or use a single subquery/counter cache rather than loading up to 10 ActiveRecord message records per conversation to call.count.
Environment
- Chatwoot Version: v4.18.0 / develop
- Database: PostgreSQL 14+
- Deployment: Self-hosted Linux / Docker / Cloud
Source: chatwoot/chatwoot