Fix N+1 query pattern in attachment fetching for activities #341
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
The activities API was executing O(n) database queries to fetch attachments, calling
get_attachments()once per comment/communication in a loop. For leads with many activities, this caused significant overhead.Changes
New batch fetching function
get_attachments_batch(doctype, names)that fetches attachments for multiple documents in a single query using SQLINclauseUpdated
get_opportunity_activities()andget_lead_activities()get_attachments()calls with O(1) dictionary lookupsBefore:
After:
Impact
Reduces queries from O(n) to O(1) — exactly 2 queries per function regardless of activity count. Estimated 15-25% performance improvement for activity timeline loads.
Original prompt
This section details on the original issue you should resolve
<issue_title>N+1 Query Pattern in get_attachments() Called Per Comment</issue_title>
<issue_description>
Metadata
next_crm/api/activities.py:127,139,157,311,331Problem Description
The
get_attachments()function is called inside loops for each comment, info_log, and communication. For a lead/opportunity with many activities, this creates numerous additional database queries.Impact Analysis
Code Location
Root Cause
get_attachments()called inside multiple loopsget_opportunity_activities()andget_lead_activities()Proposed Solution
Batch fetch attachments before the loops:
Implementation Steps
get_attachments_batch()helper functionget_attachments()calls with dictionary lookups✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.