{"id":12985,"date":"2026-06-30T06:43:54","date_gmt":"2026-06-30T06:43:54","guid":{"rendered":"https:\/\/www.greytrix.com\/blogs\/salesforce\/?p=12985"},"modified":"2026-06-29T07:58:57","modified_gmt":"2026-06-29T07:58:57","slug":"how-to-manage-apex-heap-size-in-salesforce-and-avoid-heap-size-limit-errors","status":"publish","type":"post","link":"https:\/\/www.greytrix.com\/blogs\/salesforce\/2026\/06\/30\/how-to-manage-apex-heap-size-in-salesforce-and-avoid-heap-size-limit-errors\/","title":{"rendered":"How to Manage Apex Heap Size in Salesforce and Avoid Heap Size Limit Errors"},"content":{"rendered":"\n<p>As Salesforce applications grow in complexity and handle larger datasets, Apex Heap Size Limit errors become one of the most common governor limit exceptions developers encounter.<\/p>\n\n\n\n<p>Apex heap size issues occur when a single transaction consumes more memory than Salesforce allocates. These errors are rarely caused by incorrect code. Instead, they typically arise when otherwise valid logic processes large production datasets, broad SOQL queries, complex object structures, or inefficient memory management patterns.<\/p>\n\n\n\n<p>As record volumes increase and production data becomes richer than sandbox data, even minor inefficiencies in querying, storing, or serializing data can quickly accumulate and exceed Salesforce&#8217;s strict heap limits, resulting in immediate runtime failures.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\"><strong>Salesforce Apex Heap Size Limits<\/strong><\/mark><\/h2>\n\n\n\n<p>Salesforce enforces the following heap size limits:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>6 MB for Synchronous Apex<\/li>\n\n\n\n<li>12 MB for Asynchronous Apex<\/li>\n<\/ul>\n\n\n\n<p>When these limits are exceeded, the transaction fails immediately.<\/p>\n\n\n\n<p>Heap size issues generally occur when too much data is stored in memory during a single transaction.<\/p>\n\n\n\n<p><strong>Common Causes of Apex Heap Size Errors<\/strong><\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Querying unnecessary fields<\/li>\n\n\n\n<li>Large SObject collections<\/li>\n\n\n\n<li>Heavy wrapper classes<\/li>\n\n\n\n<li>JSON serialization of full objects<\/li>\n\n\n\n<li>Passing large datasets into asynchronous jobs<\/li>\n\n\n\n<li>Static variables holding unnecessary data<\/li>\n<\/ul>\n\n\n\n<p>Let&#8217;s look at some common scenarios and their solutions.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">1. SOQL Query Design Problem<\/mark><\/strong><\/h2>\n\n\n\n<p>Querying unnecessary fields significantly increases heap usage.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>apex id=\"q1\"\nSELECT Id, Subject, Description, Internal_Notes_c\nFROM Case<\/code><\/pre>\n\n\n\n<p>Even if only the Subject field is required, querying every field loads the complete record into memory.<\/p>\n\n\n\n<p><strong>Solution<\/strong><\/p>\n\n\n\n<p>Query only the fields your logic actually uses.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>apex id=\"q2\"\nSELECT Id, Subject\nFROM Case<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">2. Large Collections Problem<\/mark><\/strong><\/h2>\n\n\n\n<p>Storing complete SObjects inside Maps or Collections consumes a large amount of memory.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>apex id=\"q3\"\nMap&lt;id, Account> accountMap = new Map&lt;Id, Account>(accounts);<\/code><\/pre>\n\n\n\n<p>This stores every field of the <strong>Account<\/strong> object, increasing heap usage unnecessarily.<\/p>\n\n\n\n<p><strong>Solution<\/strong><\/p>\n\n\n\n<p>Store only the values you actually need.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>apex id=\"q4\"\nMap&lt;Id, String> accountNameMap = new Map&lt;Id, String>();\n\nfor(Account acc : accounts){\n    accountNameMap.put(acc.Id, acc.Name);\n    }<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">3. Wrapper Classes Problem<\/mark><\/strong><\/h2>\n\n\n\n<p>Wrapper classes that contain full SObjects can quickly consume heap space, especially when processing thousands of records.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>apex id=\"q5\"\npublic class OppWrapper {\npublic Opportunity opp;\npublic Account acc;\npublic List&lt;Task> tasks;\n}<\/code><\/pre>\n\n\n\n<p>This approach becomes expensive with large datasets.<\/p>\n\n\n\n<p><strong>Solution<\/strong><\/p>\n\n\n\n<p>Use lightweight wrapper structures and load additional data only when necessary.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>apx id=\"q6\"\npublic class OppWrapper{\npublic Id oppId;\npublic String oppName;\npublic String accountName;\n}<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">\u00a04. Async Apex Serialization Problem<\/mark><\/strong><\/h2>\n\n\n\n<p>Passing complete SObjects into Queueable Apex increases serialization overhead.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>System.enqueueJob(new JobProcessor(opportunityList);<\/code><\/pre>\n\n\n\n<p><strong>Solution<\/strong><\/p>\n\n\n\n<p>Pass only record IDs to asynchronous jobs.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>Set&lt;Id> oppIds = new Set&lt;Id>();\n\nfor(Opportunity opp : opportunityList){\noppIds.add(opp.Id):\n\n}\nSystem.enqueueJob(new JobProcessor(oppIds);<\/code><\/pre>\n\n\n\n<p>Re-query the required records inside the Queueable class instead of serializing the entire object.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">\u00a05. JSON Serialization Problem<\/mark><\/strong><\/h2>\n\n\n\n<p>Serializing full SObjects duplicates memory.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>String payload = JSON.serialize(leadRecord);<\/code><\/pre>\n\n\n\n<p>This keeps both:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>SObject in memory<\/li>\n\n\n\n<li>Serialized JSON string<\/li>\n<\/ul>\n\n\n\n<p><strong>\u00a0Solution<\/strong><\/p>\n\n\n\n<p>Use lightweight DTO (Data Transfer Object) classes instead of serializing full SObjects.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public class LeadDTO {\npublic String firstName;\npublic String lastName;\npublic String email;\npublic String company;\n}\n\nLead l = &#91;SELECT FirstName, LastName, Email, Company FROM Lead WHERE Id = :leadId];\nLeadDTO dto = new LeadDTO();\ndto.firstName = l.FirstName;\ndto.lastName = l.LastName;\ndto.email = l.Email;\ndto.company = l.Company;\n\nString payload = JSON.serialize(dto);\n<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\"><strong><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">6. Static Variables Problem<\/mark><\/strong><\/h2>\n\n\n\n<p>Large static variables remain in memory throughout the transaction and can significantly increase heap consumption.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>public static List&lt;Account> processedAccounts = new List&lt;Account>();<\/code><\/pre>\n\n\n\n<p><strong>Solution<\/strong><\/p>\n\n\n\n<p>Use static variables only for flags or small utility values, and clear them whenever possible after use.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>processedAccounts.clear();\nprocessedAccounts = null;<\/code><\/pre>\n\n\n\n<p><strong>Best Practices for Managing Apex Heap Size<\/strong><\/p>\n\n\n\n<p>To build scalable and memory-efficient Apex applications, follow these best practices:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Query only the required fields in SOQL.<\/li>\n\n\n\n<li>Avoid storing unnecessary SObjects in collections.<\/li>\n\n\n\n<li>Use lightweight wrapper classes or DTOs.<\/li>\n\n\n\n<li>Pass record IDs instead of entire objects to asynchronous Apex.<\/li>\n\n\n\n<li>Avoid serializing complete SObjects when not required.<\/li>\n\n\n\n<li>Keep static variables minimal and clear them after use.<\/li>\n\n\n\n<li>Process large datasets using Batch Apex where appropriate.<\/li>\n\n\n\n<li>Monitor heap usage during development using debug logs.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\"><strong><mark style=\"background-color:rgba(0, 0, 0, 0)\" class=\"has-inline-color has-vivid-red-color\">Conclusion<\/mark><\/strong><\/h2>\n\n\n\n<p>Apex heap size errors are not random failures &#8211; they occur when a transaction consumes more memory than Salesforce allows.<\/p>\n\n\n\n<p>By designing your Apex code to retrieve only the required data, using lightweight data structures, minimizing serialization, and carefully managing memory throughout each transaction, you can build applications that are scalable, efficient, and production-ready.<\/p>\n\n\n\n<p>Effective heap size management is a fundamental Salesforce best practice that not only helps avoid governor limit exceptions but also improves application performance, maintainability, and reliability as your data continues to grow.<\/p>\n\n\n\n<p>By following the above blog instructions, you will be able to learn \u201c<strong>How to Manage Apex Heap Size in Salesforce and Avoid Heap Size Limit Errors<\/strong>\u201c. If you still have queries or any related problems, don\u2019t hesitate to contact us at <a href=\"mailto:salesforce@greytrix.com\" target=\"_blank\" rel=\"noreferrer noopener\">salesforce@greytrix.com<\/a>. More details about our integration product are available on <a href=\"https:\/\/www.greytrix.com\/salesforce-cloud-services\/\" target=\"_blank\" rel=\"noreferrer noopener\">our website<\/a> and <a href=\"https:\/\/appexchange.salesforce.com\/appxListingDetail?listingId=a0N30000000psM5EAI\" target=\"_blank\" rel=\"noreferrer noopener\">Salesforce AppExchange<\/a>.<br>We hope you may find this blog resourceful and helpful. However, if you still have concerns and need more help, please contact us at <a href=\"mailto:salesforce@greytrix.com\" target=\"_blank\" rel=\"noreferrer noopener\">salesforce@greytrix.com<\/a>.<\/p>\n\n\n\n<p style=\"text-align: justify\"><b>About Us<\/b><\/br>\n<p><a href=\"https:\/\/www.greytrix.com\/\">Greytrix<\/a> \u2013 a globally recognized and one of the oldest Sage Development Partner and a Salesforce Product development partner offers a wide variety of integration products and services to the end users as well as to the Partners and Sage PSG across the globe. We offer Consultation, Configuration, Training and support services in out-of-the-box functionality as well as customizations to incorporate custom business rules and functionalities that require apex code incorporation into the Salesforce platform.<br><br> Greytrix has some unique solutions for Cloud CRM such as <a href=\"\">Salesforce Sage integration<\/a> for <a href=\"https:\/\/www.greytrix.com\/sage-x3-erp\/integration\/\">Sage X3<\/a>, <a href=\"https:\/\/www.greytrix.com\/salesforce-cloud-services\/sage-100-integration\/\">Sage 100<\/a> and <a href=\"https:\/\/www.greytrix.com\/salesforce-cloud-services\/sage-300-integration\/\">Sage 300 (Sage Accpac)<\/a>. We also offer best-in-class Cloud CRM <a href=\"https:\/\/www.greytrix.com\/salesforce-cloud-services\/crm-development\/\">Salesforce customization and development services<\/a> along with services such as Salesforce <a href=\"https:\/\/www.greytrix.com\/salesforce-cloud-services\/data-migration-support\/\">Data Migration<\/a>, <a href=\"https:\/\/www.greytrix.com\/salesforce-cloud-services\/crm-development\/\">Integrated App development<\/a>, Custom App development and Technical Support business partners and end users. Salesforce Cloud CRM integration offered by Greytrix works with Lightning web components and supports standard opportunity workflow. Greytrix GUMU&#x2122; integration for Sage ERP \u2013 Salesforce is a 5-star rated app listed on <a href=\"https:\/\/appexchange.salesforce.com\/appxListingDetail?listingId=a0N30000000psM5EAI\" target=\"_blank\" rel=\"noopener\">Salesforce AppExchange<\/a>.<br> The GUMU&#x2122; Cloud framework by Greytrix forms the backbone of cloud integrations that are managed in real-time for processing and execution of application programs at the click of a button.<br><br> For more information on our Salesforce products and services, contact us at <a href=\"mailto:salesforce@greytrix.com\">salesforce@greytrix.com<\/a>. We will be glad to assist you.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>As Salesforce applications grow in complexity and handle larger datasets, Apex Heap Size Limit errors become one of the most common governor limit exceptions developers encounter. Apex heap size issues occur when a single transaction consumes more memory than Salesforce allocates. These errors are rarely caused by incorrect code. Instead, they typically arise when otherwise\u2026 <span class=\"read-more\"><a href=\"https:\/\/www.greytrix.com\/blogs\/salesforce\/2026\/06\/30\/how-to-manage-apex-heap-size-in-salesforce-and-avoid-heap-size-limit-errors\/\">Read More &raquo;<\/a><\/span><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3],"tags":[13,2318,3432,3413,3419,3424,3436,3255,3429,3416,31,3431,3414,3423,3425,3415,3427,2158,367,2467,3020,3420,3418,2935,3083,3012,392,3428,3421,3422,3430,3433,2567,3314,3435,3434,3417,3426],"class_list":["post-12985","post","type-post","status-publish","format-standard","hentry","category-salesforce-srv","tag-apex","tag-apex-best-practices","tag-apex-collections-best-practices","tag-apex-heap-size","tag-apex-heap-size-too-large","tag-apex-memory-management","tag-apex-optimization-techniques","tag-apex-programming","tag-apex-scalability","tag-async-apex","tag-batch-apex","tag-efficient-soql-queries","tag-governor-limits","tag-heap-size-limit-error-salesforce","tag-json-serialization-salesforce","tag-lightning-web-components","tag-optimize-apex-performance","tag-queueable-apex","tag-salesforce","tag-salesforce-admin","tag-salesforce-apex-best-practices","tag-salesforce-apex-heap-management","tag-salesforce-architecture","tag-salesforce-coding-best-practices","tag-salesforce-developer","tag-salesforce-developer-guide","tag-salesforce-development","tag-salesforce-governor-limit-errors","tag-salesforce-governor-limits","tag-salesforce-heap-size-limit","tag-salesforce-large-data-volume","tag-salesforce-memory-optimization","tag-salesforce-performance","tag-salesforce-performance-optimization","tag-salesforce-performance-tuning","tag-salesforce-runtime-exceptions","tag-soql-optimization","tag-wrapper-classes-apex"],"_links":{"self":[{"href":"https:\/\/www.greytrix.com\/blogs\/salesforce\/wp-json\/wp\/v2\/posts\/12985","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.greytrix.com\/blogs\/salesforce\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.greytrix.com\/blogs\/salesforce\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.greytrix.com\/blogs\/salesforce\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.greytrix.com\/blogs\/salesforce\/wp-json\/wp\/v2\/comments?post=12985"}],"version-history":[{"count":12,"href":"https:\/\/www.greytrix.com\/blogs\/salesforce\/wp-json\/wp\/v2\/posts\/12985\/revisions"}],"predecessor-version":[{"id":13009,"href":"https:\/\/www.greytrix.com\/blogs\/salesforce\/wp-json\/wp\/v2\/posts\/12985\/revisions\/13009"}],"wp:attachment":[{"href":"https:\/\/www.greytrix.com\/blogs\/salesforce\/wp-json\/wp\/v2\/media?parent=12985"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.greytrix.com\/blogs\/salesforce\/wp-json\/wp\/v2\/categories?post=12985"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.greytrix.com\/blogs\/salesforce\/wp-json\/wp\/v2\/tags?post=12985"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}