LearnFrenzy
Sign in Take a free test

Governor Limits and Bulkification · Lesson 23 of 41

Apex Governor Limits Explained

5 min read Updated Nov 8, 2026 Saurabh Samir

Salesforce is multitenant: your org shares servers and databases with many others. To keep one tenant's code from slowing everyone down, every Apex transaction runs with a budget – the governor limits. Go over any of them and the platform stops the transaction immediately with an exception you can't catch. They feel restrictive at first; after a while you'll see that code written within them is simply efficient code.

In this lesson

  • The per-transaction limits that matter most
  • Synchronous vs asynchronous limits
  • Measuring usage with the Limits class
  • What happens when you exceed a limit
  • Org-wide (24-hour) limits

The limits you'll meet

Per transactionSynchronousAsynchronous
SOQL queries100200
Records retrieved by SOQL50,00050,000
SOSL searches2020
DML statements150150
Records processed by DML10,00010,000
CPU time10,000 ms60,000 ms
Heap size6 MB12 MB
Callouts (HTTP)100100
Total callout time120 s120 s
Queueable jobs enqueued501 (from a Queueable)
@future calls500 (from future/batch)
Emails sent with sendEmail10 calls10 calls

"Asynchronous" means Batch, Queueable, @future and Scheduled Apex. Higher CPU, heap and query limits are one of the main reasons to move heavy work into async jobs.

Measuring with the Limits class

Every limit has a pair of methods: Limits.getX() for what you've used and Limits.getLimitX() for the maximum:

System.debug('Start: ' + Limits.getQueries() + '/' + Limits.getLimitQueries() + ' queries, '
    + Limits.getDmlStatements() + '/' + Limits.getLimitDmlStatements() + ' DML');

List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) accounts.add(new Account(Name = 'Limits demo ' + i));
insert accounts;

List<Account> fetched = [SELECT Id, Name FROM Account WHERE Name LIKE 'Limits demo%'];
Map<Id, Account> byId = new Map<Id, Account>(fetched);

System.debug('After: ' + Limits.getQueries() + ' query, ' + Limits.getQueryRows() + ' rows queried');
System.debug('DML: ' + Limits.getDmlStatements() + ' statement, ' + Limits.getDmlRows() + ' rows');
System.debug('Heap under 6 MB? ' + (Limits.getHeapSize() < Limits.getLimitHeapSize()));
System.debug('CPU budget: ' + Limits.getLimitCpuTime() + ' ms');

Debug log

Start: 0/100 queries, 0/150 DML
After: 1 query, 200 rows queried
DML: 1 statement, 200 rows
Heap under 6 MB? true
CPU budget: 10000 ms

Two hundred records saved with one DML statement and read with one query. The numbers don't grow with the record count – that's what bulk-safe code looks like.

When you exceed a limit

insert new Account(Name = 'Limit test');
Integer done = 0;
for (Integer i = 1; i <= 160; i++) {
    update new Account(Id = [SELECT Id FROM Account LIMIT 1].Id, Description = 'touch ' + i);   // a query AND a DML per loop
    done = i;
}
System.debug('Finished ' + done + ' iterations');      // never reached

Debug log

System.LimitException: Too many SOQL queries: 101

The query limit tripped first: the code made one query per iteration, and query number 101 – in iteration 101 – ended the transaction. Everything it had done, including 100 successful updates, was rolled back. That's why limits must be designed for up front, not handled afterwards.

Checking before a risky operation

You can't catch a LimitException, but you can look before you leap – for example in a utility that may be called from contexts where other code has already used most of the budget:

// SafeLogger.cls
public with sharing class SafeLogger {
    public static Boolean canQuery(Integer needed) {
        return Limits.getQueries() + needed <= Limits.getLimitQueries();
    }
    public static Boolean canDml(Integer statements) {
        return Limits.getDmlStatements() + statements <= Limits.getLimitDmlStatements();
    }
}
for (Integer i = 0; i < 98; i++) Integer n = [SELECT COUNT() FROM Account];   // pretend other code used 98 queries

if (SafeLogger.canQuery(5)) {
    System.debug('enough queries left');
} else {
    System.debug('Only ' + (Limits.getLimitQueries() - Limits.getQueries()) + ' queries left – deferring work to a Queueable');
}

Debug log

Only 2 queries left – deferring work to a Queueable

The quiet killers: CPU time and heap

  • CPU time counts the time your Apex (and the declarative automation it triggers) spends executing – not time waiting for the database or callouts. Nested loops over large lists are the usual culprit: 2,000 × 2,000 comparisons is four million iterations. Use Maps for lookups instead.
  • Heap is the memory your variables use. Large query results, big JSON strings and attachments fill it. Select only the fields you need, use SOQL for loops for large sets, and clear collections you no longer need.

Org-wide limits

Some limits apply to the whole org over 24 hours rather than to one transaction:

LimitScope
Asynchronous Apex executions (Batch, Queueable, future, Scheduled)250,000 per 24 h, or 200 × user licences if higher
API requestsdepends on edition and licences
Single emails sent to external addresses5,000 per day
Scheduled Apex jobs100 scheduled at a time
Batch jobs5 queued or active at once (plus up to 100 in the flex queue)

Check current org usage with OrgLimits.getMap() in Apex, or Setup → Company Information. Values change between releases – Salesforce's "Execution Governors and Limits" page is the definitive reference.

Practice

Try it yourself

  1. A trigger works when users edit one record but fails with "Too many SOQL queries: 101" during a data import. What's the likely cause?

    Show answer

    A query inside a loop over Trigger.new. With one record it's one query; an import fires the trigger with 200 records, so 200 queries. Bulkify: query once for all records (next lesson).

  2. Which limits get higher when the same code runs in a Queueable instead of synchronously?

    Show answer

    SOQL queries (100 → 200), CPU time (10 s → 60 s) and heap (6 MB → 12 MB). DML statements and rows stay the same.

Quick check

How many SOQL queries are allowed in a synchronous transaction?

100.

Can you catch a LimitException?

No – the transaction ends and all changes roll back.

Which method tells you how many DML statements you've used?

Limits.getDmlStatements().

Summary

  • Every transaction has limits on queries, DML, CPU, heap and more.
  • Async contexts get higher CPU, heap and query limits.
  • Use Limits.getX() and getLimitX() to measure and check headroom.
  • Exceeding a limit rolls everything back – design to stay within them.

Finished this lesson?

Mark it complete to track your progress, then carry on with the next lesson.

Next lesson

Search LearnFrenzy

Esc

Quick links