is live. Lifetime & Yearly plans on offer. thankful for you ๐Ÿงก

Get the Black Friday deal

Apex

Governor Limits in Salesforce: What They Are and How to Stay Under Them

Governor limits in Salesforce cap SOQL, DML, CPU time and heap per transaction. See the numbers, the code that breaks them, and how to fix each.

By Teja, ex-Salesforce engineer ยท Updated November 24, 2026 ยท 10 min read

Apex

Governor limits in Salesforce are runtime caps that the Apex engine enforces on every transaction. Examples include 100 SOQL queries (200 in async code), 150 DML statements, 10 seconds of CPU time (60 seconds async) and a 6 MB heap (12 MB async). They exist because thousands of orgs share the same servers and database, so no single org's code can be allowed to use up resources the others need. You stay under them by writing bulkified code: query and save records in collections outside loops, use maps for lookups, and move large or slow work into asynchronous Apex.

This guide is for developers writing Apex for production orgs. It covers the limits behind most failures, the code patterns that trigger them, and the fix for each.

Why Salesforce enforces governor limits

Salesforce is a multitenant platform. Your org's data sits in the same database as other customers' data, and your Apex runs on application servers shared with other orgs. If one org ran a trigger with a runaway loop or a query pulling millions of rows, every other tenant on that instance would slow down.

The platform does not try to schedule around bad code. It meters each transaction instead, and when a counter goes over its ceiling it throws a System.LimitException and rolls the whole transaction back. Two points shape how you write code:

  • You can't catch a limit exception. A try/catch block will not save you. Once you hit the limit, the transaction is over, so the only fix is to avoid reaching it.
  • Limits apply to the whole transaction, not to each class. One save on an Account can fire a trigger, a flow, a second trigger on Contact and a validation-driven update. All of that shares one budget of 100 queries. A trigger that uses 30 queries looks fine alone. Add three more automations and it fails.

The per-transaction limits you will actually hit

These numbers come from Salesforce's Execution Governors and Limits page in the Apex Developer Guide. Salesforce adjusts limits from time to time, so check that page when you need the exact current value.

LimitSynchronousAsynchronous
SOQL queries issued100200
Total records retrieved by SOQL50,00050,000
Records retrieved by Database.getQueryLocator10,00010,000
SOSL queries issued2020
DML statements issued150150
Records processed by DML10,00010,000
CPU time on Salesforce servers10,000 ms60,000 ms
Heap size6 MB12 MB
Callouts (HTTP or web service)100100
Cumulative callout timeout120 seconds120 seconds
@future method calls500 in batch and future contexts
Queueable jobs added with System.enqueueJob501
sendEmail invocations1010
Trigger stack depth (recursive inserts, updates, deletes)1616
Maximum transaction execution time10 minutes10 minutes

Some details that trip people up:

  • CPU time excludes database time. Time spent inside SOQL, SOSL and DML doesn't count toward the 10,000 ms, and neither does time spent waiting on a callout. CPU time measures your Apex logic: loops, string building, JSON parsing, sorting.
  • The 50,000 row limit is cumulative. Five queries returning 12,000 rows each add up to 60,000 and fail, even though no single query was large.
  • Triggers run in chunks of up to 200 records. A Data Loader job or a bulk API call hands your trigger 200 records at a time. If your code runs one query per record, the 101st record breaks it.

Pattern 1: SOQL inside a loop

This is the most common cause of System.LimitException: Too many SOQL queries: 101.

What breaks:

trigger ContactTrigger on Contact (before insert) {
    for (Contact c : Trigger.new) {
        Account a = [SELECT Id, Industry FROM Account WHERE Id = :c.AccountId];
        c.Description = a.Industry;
    }
}

Insert one contact from the UI and it works. Insert 200 through Data Loader and it fails on the 101st query.

The fix: gather the IDs first, run one query, then read from a map.

trigger ContactTrigger on Contact (before insert) {
    Set<Id> accountIds = new Set<Id>();
    for (Contact c : Trigger.new) {
        if (c.AccountId != null) {
            accountIds.add(c.AccountId);
        }
    }

    Map<Id, Account> accountsById = new Map<Id, Account>(
        [SELECT Id, Industry FROM Account WHERE Id IN :accountIds]
    );

    for (Contact c : Trigger.new) {
        Account a = accountsById.get(c.AccountId);
        if (a != null) {
            c.Description = a.Industry;
        }
    }
}

That's one query whether the batch has 1 record or 200. The same rule covers methods called from a loop: if getDiscount(opp) runs a query internally, calling it inside a loop is still a query in a loop. Our post on Apex bulkification and the "Too many SOQL queries: 101" error walks through more versions of this pattern.

Pattern 2: DML inside a loop

What breaks:

for (Opportunity opp : closedWonOpps) {
    Task t = new Task(WhatId = opp.Id, Subject = 'Send welcome kit');
    insert t;
}

Each insert counts as one DML statement. Once there are more than 150 opportunities you get Too many DML statements: 151.

The fix: build a list and commit it once.

List<Task> tasks = new List<Task>();
for (Opportunity opp : closedWonOpps) {
    tasks.add(new Task(WhatId = opp.Id, Subject = 'Send welcome kit'));
}
if (!tasks.isEmpty()) {
    insert tasks;
}

One statement inserts up to 10,000 rows. If you need partial success, so one bad record doesn't roll back the rest, use Database.insert(tasks, false) and inspect the SaveResult array.

Platform event publishing works the same way. EventBus.publish calls count against the DML statement limit, so publish a list, not one event per iteration.

Pattern 3: Nested loops that burn CPU time

Apex CPU time limit exceeded usually comes from Apex logic. The classic cause is matching two lists with nested loops.

What breaks:

for (Account acc : accounts) {
    for (Opportunity opp : opportunities) {
        if (opp.AccountId == acc.Id) {
            acc.Total_Pipeline__c += opp.Amount;
        }
    }
}

With 2,000 accounts and 20,000 opportunities that is 40 million comparisons.

The fix: group once with a map, then do direct lookups.

Map<Id, Decimal> pipelineByAccount = new Map<Id, Decimal>();
for (Opportunity opp : opportunities) {
    Decimal running = pipelineByAccount.containsKey(opp.AccountId)
        ? pipelineByAccount.get(opp.AccountId) : 0;
    pipelineByAccount.put(opp.AccountId, running + (opp.Amount == null ? 0 : opp.Amount));
}
for (Account acc : accounts) {
    acc.Total_Pipeline__c = pipelineByAccount.containsKey(acc.Id)
        ? pipelineByAccount.get(acc.Id) : 0;
}

Better still, let the database do the math. An aggregate query doesn't use Apex CPU time for the summing:

for (AggregateResult ar : [
    SELECT AccountId, SUM(Amount) total
    FROM Opportunity
    WHERE AccountId IN :accountIds
    GROUP BY AccountId
]) {
    // read ar.get('AccountId') and ar.get('total')
}

Other common CPU drains:

  • Parsing large JSON payloads with JSON.deserializeUntyped and then walking the maps by hand
  • String concatenation inside large loops (collect into a List<String> and call String.join)
  • Several automations on the same object, each doing a little work, which add up within one transaction
  • Debug statements that serialize large objects

Pattern 4: Loading too much into memory (heap size)

What breaks:

List<Case> allCases = [SELECT Id, Description, Subject FROM Case WHERE CreatedDate = LAST_N_DAYS:365];
for (Case c : allCases) {
    // process
}

Long text fields such as Description fill the 6 MB heap quickly. You get Apex heap size too large.

Fixes, in order of preference:

  1. Select fewer fields. Leave out long text and rich text fields unless you need them.
  2. Use a SOQL for loop. It fetches records in chunks of 200 and lets earlier chunks be garbage collected:
for (List<Case> chunk : [SELECT Id, Subject FROM Case WHERE CreatedDate = LAST_N_DAYS:365]) {
    // process 200 at a time
}

The rows still count toward the 50,000 row limit. The SOQL for loop only fixes memory.

  1. Move to Batch Apex when the volume really is large. Each execute call gets its own set of limits, and Database.getQueryLocator in start can iterate up to 50 million records.
  2. Clear references you no longer need (bigList = null;) inside long methods so the memory can be reclaimed.

Pattern 5: Trigger recursion

A trigger on Account updates related Contacts. A trigger on Contact updates the parent Account. Each update re-fires the other trigger, and you hit either the SOQL limit or Maximum trigger depth exceeded (the stack depth limit of 16).

The fix: track which records have already been processed in a static variable, which lives for the length of the transaction.

public class AccountTriggerHandler {
    private static Set<Id> processedIds = new Set<Id>();

    public static void afterUpdate(List<Account> newList) {
        List<Account> toProcess = new List<Account>();
        for (Account a : newList) {
            if (!processedIds.contains(a.Id)) {
                processedIds.add(a.Id);
                toProcess.add(a);
            }
        }
        if (toProcess.isEmpty()) return;
        // work on toProcess only
    }
}

Avoid the single static Boolean flag you see in many examples. It blocks the second chunk of 200 records in a bulk load, so records 201 onward silently skip your logic. A Set<Id> handles chunking correctly.

The bigger fix is structural: one trigger per object, delegating to a handler class that controls order and re-entry. Teja covers this structure in the free Apex Triggers Framework 101 course (8 episodes, about half an hour), building it line by line in a real org.

Pattern 6: Callouts and async jobs inside loops

What breaks:

for (Order__c o : orders) {
    OrderSyncService.sendAsync(o.Id);   // an @future(callout=true) method
}

More than 50 orders and the @future limit fails. If this runs from a batch job, @future calls aren't allowed at all.

The fix: pass the whole collection to a single async job, and make one callout carrying many records if the external API supports it.

public class OrderSyncJob implements Queueable, Database.AllowsCallouts {
    private List<Id> orderIds;
    public OrderSyncJob(List<Id> orderIds) { this.orderIds = orderIds; }

    public void execute(QueueableContext ctx) {
        // build one request body for all orders, make one callout
        // if more remain, chain one new job (only 1 enqueue allowed from async context)
    }
}

System.enqueueJob(new OrderSyncJob(new List<Id>(orderIdSet)));

Keep the 120 second cumulative callout timeout in mind. Ten slow calls at 15 seconds each already exceed it. For true bulk data movement, the Bulk API 2.0 or Platform Events are often a better fit than callouts from triggers. Both are covered in the Integration Master Course, along with REST in Apex and Named and External Credentials.

How to check limit usage before production does it for you

The fastest check you can run anywhere is the platform's own Limits class, which reports live usage inside your transaction:

System.debug('SOQL: ' + Limits.getQueries() + ' / ' + Limits.getLimitQueries());
System.debug('DML: ' + Limits.getDmlStatements() + ' / ' + Limits.getLimitDmlStatements());
System.debug('CPU ms: ' + Limits.getCpuTime() + ' / ' + Limits.getLimitCpuTime());
System.debug('Heap: ' + Limits.getHeapSize() + ' / ' + Limits.getLimitHeapSize());

Use it in three places:

  1. Debug logs. Every log ends with a LIMIT_USAGE_FOR_NS block showing usage against each limit. Run your scenario with 200 records and read that block first.
  2. Defensive code. Before an expensive optional step, check headroom and defer the work to a Queueable if you're close:
if (Limits.getQueries() > Limits.getLimitQueries() - 10) {
    System.enqueueJob(new DeferredWorkJob(recordIds));
    return;
}
  1. Test classes. This is where most limit bugs should be caught.

Write tests that actually find limit problems

A test that inserts one record proves nothing about limits. Tests that catch these bugs follow three rules:

  • Insert at least 200 records so the trigger receives a full chunk. Insert 201 or more if you want to see chunking behavior.
  • Wrap the action in Test.startTest() and Test.stopTest(). The code between them gets a fresh set of governor limits, so test data setup doesn't eat into the budget of the code you're testing. stopTest() also forces async jobs to run so you can assert on their results.
  • Assert on outcomes, not coverage. A test with no assertions can reach 75% coverage and still ship a query-in-a-loop.
@IsTest
static void bulkInsertStaysUnderLimits() {
    Account acc = new Account(Name = 'Bulk Test');
    insert acc;

    List<Contact> contacts = new List<Contact>();
    for (Integer i = 0; i < 200; i++) {
        contacts.add(new Contact(LastName = 'C' + i, AccountId = acc.Id));
    }

    Test.startTest();
    insert contacts;
    Integer queriesUsed = Limits.getQueries();
    Test.stopTest();

    Assert.isTrue(queriesUsed < 10, 'Trigger should not query per record');
}

Apex Test Fest goes further into async tests, System.runAs, the Assert class and callout mocks, which you need for testing the Queueable callout pattern above.

A quick review checklist before you deploy

CheckWhat to look for
No SOQL in loopsIncludes queries hidden inside helper methods called from loops
No DML in loopsCollect into lists, commit once
Maps for lookupsNo nested loops over two record lists
Selective queriesFilter on indexed fields, select only needed fields
Recursion guardSet<Id>, not a single Boolean
Async in bulkOne Queueable or batch per transaction, not one per record
Bulk tests200+ records, startTest/stopTest, real assertions
Whole-transaction viewCount flows and other triggers on the same object

How Salesforce Casts fits in

Governor limits are mostly a habit problem. Developers who learned Apex from single-record examples write single-record code. Every Salesforce Casts course is built live in a real org, line by line, with a GitHub repo of the source code, so you see bulkified patterns written and debugged instead of pasted from slides. If you're working through Apex in order, the Learn Apex page lays out the topics in sequence. Every plan unlocks every course, and questions go to a private discussion group rather than live classes.

FAQ

Are governor limits the same in sandbox and production?

Yes. Per-transaction Apex limits are identical in sandboxes, developer orgs and production. What differs is data volume: a sandbox with 50 test records hides problems that 50,000 production records expose. Test with realistic volumes before you deploy.

Can I ask Salesforce to raise a governor limit?

Not for the per-transaction Apex limits like SOQL queries, DML statements, CPU time or heap. Those are fixed for every org. Some org-wide allocations, such as daily API requests, scale with your licenses or can be purchased, but code that hits per-transaction limits has to be redesigned.

Do Flows count toward the same governor limits as Apex?

Yes. Record-triggered flows run in the same transaction as your triggers and use the same SOQL, DML and CPU budgets. A Get Records element inside a loop in Flow causes the same "101 SOQL queries" failure as SOQL in a loop in Apex.

Why does my code work for one record but fail on data loads?

Triggers receive records in chunks of up to 200. Code that runs one query or one DML statement per record uses 1 of each for a single UI save and 200 for a bulk load. Bulkify the code and test with 200 or more records to reproduce the failure.

Does async Apex solve every limit problem?

No. Async contexts give you higher SOQL, CPU and heap limits, and batch Apex resets limits for each chunk, but DML statements stay at 150 and a Queueable can enqueue only one more job. Moving bad code into a Queueable delays the failure without fixing it. Bulkify first, then go async for volume or callouts.

Are governor limits asked about in developer interviews?

Almost always. Expect questions on the core numbers, bulkification, and when to choose future, Queueable or batch Apex. The async Apex interview questions page covers the async side in question-and-answer form.

Next step

Open the debug log for your busiest trigger, run it with 200 records, and read the LIMIT_USAGE_FOR_NS block. If the SOQL or DML count rises with the record count, start with the free Apex Triggers Framework 101 course and refactor that trigger first.

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion โ€” one subscription.

Keep going

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts