#16061·chatwoot

perf: Severe N+1 query loop and high view latency in _conversation.json.jbuilder (350+ queries per page of 25 conversations)

Author: md-riazCreated Sep 29, 2026Updated Sep 29, 2026

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:

  1. unread_count via conversation.unread_incoming_messages.count (Line 63):

    ruby
    # app/models/conversation.rb:202
    def unread_incoming_messages
      unread_messages.where(account_id: account_id).incoming.last(10)
    end

    Calling .last(10) on the relation generates SELECT ... FROM messages WHERE conversation_id = ? ... ORDER BY id DESC LIMIT 10 per conversation. For 25 conversations, this generates 25 separate queries to messages.

  2. last_non_activity_message (Line 64):

    ruby
    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 1 per conversation (another 25 queries).

  3. last_message lookup with blob attachments (Lines 36-39):

    ruby
    last_message = conversation.messages.where(account_id: conversation.account_id)
                               .includes([{ attachments: [{ file_attachment: [:blob] }] }])
                               .reorder(created_at: :desc, id: :desc).first

    Issues queries for messages, active storage attachments, and blobs for each conversation.

  4. Sender, Assignee, and Contact Inbox associations (Lines 5-27):

    • conversation.contact_inbox&.hmac_verified queries contact_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

  1. Eager Loading in ConversationFinder: Pre-load contact_inbox, contact => { avatar_attachment: :blob }, assigned_entity => { avatar_attachment: :blob }, and team in conversations_base_query.
  2. 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_id on the conversations record during message creation.
  3. 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