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. It covers the limits that apply inside a single Apex transaction. These differ from the daily API request limit, which counts calls made from outside Salesforce.
What a governor limit is
A governor limit is a cap that Salesforce enforces on one Apex transaction. A transaction is one unit of work, such as a trigger firing after a record save, a REST call into an Apex class, or one execution of a batch job chunk. Every transaction starts with zero usage, and the counters reset when it ends.
Because many customers share the same servers, one runaway loop could slow down everyone else. Governor limits stop that. If your code goes over a limit, Salesforce throws a System.LimitException. You cannot catch this exception, so the whole transaction fails and all of its database changes roll back.
Common limits
The numbers below are the values for synchronous Apex. Asynchronous Apex, such as Batch Apex and @future methods, usually gets higher ceilings. Check the current Apex Developer Guide for exact values, because Salesforce can change them.
| Resource | Synchronous limit | Typical cause of hitting it |
|---|---|---|
| SOQL queries issued | 100 | A query inside a `for` loop |
| Records returned by SOQL | 50,000 | Querying without a selective filter |
| DML statements | 150 | An insert or update inside a loop |
| Records processed by DML | 10,000 | Updating too many records in one transaction |
| CPU time | 10,000 ms | Nested loops, heavy calculation |
| Heap size | 6 MB | Holding large collections in memory |
| Callouts | 100 | One HTTP callout per record |
Two points matter for design. First, the limits apply per transaction, not per user or per day. Second, a trigger handles up to 200 records at a time, so code that works for one record can fail for 200.
The classic failure: queries in a loop
This trigger runs one query for every record in Trigger.new. With 101 or more accounts in a single save, it exceeds the 100-query limit.
trigger ContactCounter on Account (before update) {
for (Account a : Trigger.new) {
// One SOQL query per account: fails at 101 records
Integer n = [SELECT COUNT() FROM Contact WHERE AccountId = :a.Id];
a.NumberOfEmployees = n;
}
}The fix is to bulkify, which means handling all records with one query and one pass.
trigger ContactCounter on Account (before update) {
Map<Id, Integer> counts = new Map<Id, Integer>();
for (AggregateResult ar : [
SELECT AccountId acc, COUNT(Id) total
FROM Contact
WHERE AccountId IN :Trigger.newMap.keySet()
GROUP BY AccountId
]) {
counts.put((Id) ar.get('acc'), (Integer) ar.get('total'));
}
for (Account a : Trigger.new) {
a.NumberOfEmployees = counts.containsKey(a.Id) ? counts.get(a.Id) : 0;
}
}This version uses one query no matter how many accounts are in the save.
How a transaction is checked
Salesforce compares each counter to its ceiling as the code runs. The check happens at the moment of use, not at the end.
Checking usage before you hit the limit
The Limits class lets code read its own usage. Each resource has a pair of methods: one for what you have used and one for the ceiling.
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());You can use these values to stop early. For example, a loop can check Limits.getQueries() < Limits.getLimitQueries() before it runs another query, then hand the remaining work to a Queueable job.
Common errors
- Too many SOQL queries: 101. A query sits inside a loop. Move it out and filter with
IN :set. - Too many DML statements: 151. Collect records in a
Listand run oneupdateafter the loop. - Apex CPU time limit exceeded. Look for nested loops over large lists. Replace inner searches with a
Maplookup. - Apex heap size too large. Query only the fields you need, and use a SOQL
forloop to process large result sets in chunks.
Exercise
A trigger on Contact runs fine when you edit one record, but fails with "Too many SOQL queries: 101" when a data load updates 200 contacts. What is the likely cause, and what is the fix?
Show answer
The trigger runs a SOQL query inside a loop over Trigger.new, so each record adds one query and the 101st exceeds the limit of 100. The fix is to collect the needed IDs into a Set, run one query with WHERE Id IN :set, store the results in a Map, and look up values from the map inside the loop.