Sub topic 5
Apex Governor Limits in a Transaction
This chapter assumes you can read basic Apex, run SOQL queries, and know that Salesforce is a shared (multitenant) platform. Earlier chapters covered why limits exist and how they are grouped. Here the focus is the limits that apply inside a single Apex transaction.
What a transaction is
A transaction is one unit of Apex work that either commits together or rolls back together. Governor limits are counted per transaction. They reset when the transaction ends.
Common ways a transaction starts:
- A trigger fires from a DML operation (insert, update, delete, undelete).
- A REST or SOAP call reaches an Apex web service.
- An Apex controller, Lightning component, or Flow invokes an Apex method.
- A scheduled job, Queueable job, or batch
executecall runs.
Everything that runs inside that one entry point shares the same counters. That includes triggers, workflow-driven updates, and helper classes. If a trigger on Account fires a second trigger on Contact, both consume from the same budget.
This is why governor limits are not the same as the daily API request limit. The daily limit counts calls coming into the org over a rolling 24-hour period. Governor limits count the work one piece of Apex does once it is running. A single API call can therefore succeed at the API level and still fail because the Apex it triggered exceeded a governor limit.
The limits you meet most often
Salesforce publishes the exact values in the Apex Developer Guide, and they can change between releases. The values below are the commonly cited synchronous ones. Confirm them for your API version before you rely on them.
| Limit | Synchronous | Asynchronous |
|---|---|---|
| SOQL queries issued | 100 | 200 |
| Records retrieved by SOQL | 50,000 | 50,000 |
| DML statements issued | 150 | 150 |
| Records processed by DML | 10,000 | 10,000 |
| CPU time | 10,000 ms | 60,000 ms |
| Heap size | 6 MB | 12 MB |
| Callouts per transaction | 100 | 100 |
Two points about this table matter in practice:
- The limit is on the number of statements, not on the number of records. One
updateof 200 records uses one DML statement. Callingupdateinside a loop over 200 records uses 200. - Asynchronous work (Queueable, Batch,
@future) gets higher ceilings for queries, CPU time, and heap. It does not get more DML statements.
Other limits exist, such as the number of @future calls, Queueable jobs enqueued, email invocations, and SOQL query rows returned by Database.getQueryLocator. Look them up when you use those features.
How a limit failure behaves
When a transaction crosses a governor limit, Salesforce throws a System.LimitException. This exception has a property that surprises many developers: you cannot catch it. A try/catch block does not handle it. The transaction is stopped, and all of its changes are rolled back.
try {
for (Integer i = 0; i < 101; i++) {
List<Account> accts = [SELECT Id FROM Account LIMIT 1];
}
} catch (Exception e) {
// Never reached for a governor limit. The transaction is aborted
// when the 101st query runs, and this block does not execute.
System.debug('Caught: ' + e.getMessage());
}The error message looks like System.LimitException: Too many SOQL queries: 101. The number in the message is the count that tripped the limit, which is one more than the allowed value.
Because you cannot recover after the fact, the defensive approach is to check consumption before you do the expensive step, and to design code so that it stays well under the ceiling.
The most common cause: work inside loops
Nearly every Too many SOQL queries and Too many DML statements error comes from running a query or a DML statement once per record. Triggers receive up to 200 records at a time, so a pattern that works for one record in a test fails during a data load.
This version breaks in bulk:
trigger ContactAfterInsert on Contact (after insert) {
for (Contact c : Trigger.new) {
// One query per contact: 200 contacts means 200 queries.
Account a = [SELECT Id, Name FROM Account WHERE Id = :c.AccountId];
a.Description = 'Has new contact: ' + c.LastName;
// One DML statement per contact.
update a;
}
}This version collects the IDs first, queries once, and updates once:
trigger ContactAfterInsert on Contact (after insert) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id, Account> accounts = new Map<Id, Account>(
[SELECT Id, Description FROM Account WHERE Id IN :accountIds]
);
List<Account> toUpdate = new List<Account>();
for (Contact c : Trigger.new) {
Account a = accounts.get(c.AccountId);
if (a != null) {
a.Description = 'Has new contact: ' + c.LastName;
toUpdate.add(a);
}
}
if (!toUpdate.isEmpty()) {
update toUpdate;
}
}The second version uses one SOQL query and at most one DML statement no matter how many contacts arrive. If two contacts share an account, the same Account record appears in the list twice. Salesforce rejects a list that contains the same ID more than once for a single update, so use a Map<Id, Account> to hold the records to update when duplicates are possible.
This pattern is called bulkification. It is the single most important habit for staying within governor limits.
Measuring usage with the Limits class
The Apex Limits class reports how much of each limit the current transaction has used. Each limit has two methods: one for current consumption (getQueries) and one for the ceiling (getLimitQueries).
System.debug('SOQL queries: ' + Limits.getQueries() + '/' + Limits.getLimitQueries());
System.debug('DML statements: ' + Limits.getDmlStatements() + '/' + Limits.getLimitDmlStatements());
System.debug('CPU time (ms): ' + Limits.getCpuTime() + '/' + Limits.getLimitCpuTime());
System.debug('Heap size (bytes): ' + Limits.getHeapSize() + '/' + Limits.getLimitHeapSize());getLimit... methods return the ceiling that applies to the current context. When the code runs in a Queueable job, Limits.getLimitQueries() returns 200. When it runs synchronously, it returns 100. This is more reliable than hard-coding a number in your own code.
You can use the same methods to make runtime decisions. For example, a helper can stop doing optional work when the transaction is close to its limit:
public class LimitGuard {
// Returns true when at least `minRemaining` SOQL queries are still available.
public static Boolean hasQueryHeadroom(Integer minRemaining) {
return (Limits.getLimitQueries() - Limits.getQueries()) >= minRemaining;
}
}A caller can then skip an optional enrichment step, or hand the work to a Queueable job, instead of risking an uncatchable failure.
Where to see the numbers
- Debug logs. At the end of each transaction, the log includes a
CUMULATIVE_LIMIT_USAGEsection. It lists used and allowed amounts per limit, grouped by namespace. Set the log level for the Apex Code category high enough to capture it. - Developer Console. The Execute Anonymous window with a log open shows the same sections, and the Limits tab in the Developer Console summarizes them.
- Your own
System.debugcalls. Place them before and after a suspect block to see which block consumes the most.
Namespaces and managed packages
Most governor limits are counted per namespace. Code from a managed package from an installed AppExchange vendor gets its own set of counters for per-transaction limits such as SOQL queries and DML statements. Your own code and the package code each get a full allowance within the same transaction.
Some limits are shared across all namespaces, including CPU time and heap size. A slow package can use CPU time that your code then does not have. In a debug log, the CUMULATIVE_LIMIT_USAGE section appears once per namespace, so you can tell whose code is responsible.
Limits that are not governor limits but behave like them
Some failures look similar but have different causes:
- Row locks.
UNABLE_TO_LOCK_ROWhappens when two transactions try to update the same record at the same time. It is a concurrency problem, not a governor limit. - Mixed DML. Setup objects (such as
User) and non-setup objects (such asAccount) cannot be changed in the same transaction. The error isMIXED_DML_OPERATION. - Callout after DML. Making an HTTP callout after uncommitted DML in the same transaction raises an error. Do the callout first, or move one of the two steps to an asynchronous job.
Choosing an async approach when limits are tight
When the work cannot fit synchronous limits, move it to an asynchronous context, which has higher ceilings.
| Option | Best for | Notes |
|---|---|---|
| Queueable Apex | A follow-up job that needs complex parameters | Can be chained. Runs with asynchronous limits. |
| Batch Apex | Processing large data sets in chunks | Each `execute` call is its own transaction with fresh limits. |
| `@future` method | Simple fire-and-forget work, such as a callout | Parameters must be primitives. Limited in how many you can call. |
| Platform Events | Decoupling a trigger from slow downstream work | Subscribers run in their own transaction. |
Batch Apex is the main tool for processing very large volumes. Because each chunk runs as a separate transaction, the counters reset between chunks.
Common mistakes
- Putting SOQL or DML inside a
forloop. - Assuming a
try/catchwill handleSystem.LimitException. - Testing a trigger with a single record only.
- Hard-coding limit numbers instead of calling
Limits.getLimit...methods. - Forgetting that triggers, flows, and process automation all share one transaction, so adding new automation to an object can push old code over its limit.
- Querying every field and every row when you only need a few. This wastes heap and CPU time even when query counts are fine.
Connecting this to API monitoring
The REST Limits resource and the Sforce-Limit-Info header describe org-wide API consumption. They do not show per-transaction Apex usage. When an API client reports an error that is not REQUEST_LIMIT_EXCEEDED, for example a System.LimitException in an error body from an Apex REST endpoint, the cause is a governor limit in your Apex, and the debug log is where you investigate.
Exercise
A trigger on Opportunity runs a SOQL query inside a for loop over Trigger.new. It passes testing with one record but fails with Too many SOQL queries: 101 when 200 opportunities are loaded through the API. Why does it fail, can a try/catch prevent the failure, and what is the fix?
Show answer
The loop runs one query per record, and 200 records in one transaction exceed the synchronous limit of 100 queries. A try/catch cannot prevent it, because System.LimitException is not catchable and the transaction is rolled back. The fix is to bulkify: collect the IDs from Trigger.new into a Set, run one query with WHERE Id IN :ids, store the results in a Map, and look up each record from the map inside the loop.
Exercise
You need the code in a shared helper class to skip an optional step when fewer than 5 SOQL queries remain. Which Limits methods do you use, and why not compare against the number 100?
Show answer
Use Limits.getLimitQueries() - Limits.getQueries() and compare the result with 5. The ceiling differs by context (100 synchronous, 200 asynchronous), so reading it from getLimitQueries() keeps the check correct wherever the helper runs.