Sub topic 17
Governor limits are shared across the transaction
This chapter assumes you can write a basic Apex trigger, know what DML is, and have seen the order of execution steps from the earlier chapters. It explains why limits are counted once for the whole save, not once per trigger or flow.
One budget for every step
Governor limits cap the resources one transaction can use. A record save is one transaction, so before-save flows, before triggers, after triggers, after-save flows, and any code they call all draw from the same budget.
These are the main limits for synchronous Apex:
| Resource | Synchronous limit |
|---|---|
| SOQL queries | 100 |
| Records returned by SOQL | 50,000 |
| DML statements | 150 |
| Records processed by DML | 10,000 |
| CPU time | 10,000 ms |
| Heap size | 6 MB |
Asynchronous Apex (queueable, batch, future) gets higher values for some of these, for example 200 queries, 12 MB of heap, and 60,000 ms of CPU. Each asynchronous job is its own transaction with a fresh budget.
A trigger that uses 40 queries looks fine alone. If a flow, a second trigger, and a parent-record update each add their own queries, the total can pass 100. The transaction then fails with a System.LimitException, which cannot be caught. The step that crosses the limit gets the error, even when another step used most of the budget.
What counts and what does not
- Each SOQL query counts as one, whatever its size. Rows returned count separately.
- Each
insert,update,delete, orDatabase.*call is one DML statement, regardless of how many records it handles. The records still count toward the 10,000-row limit. - Calling
Database.setSavepoint()orDatabase.rollback()counts as a DML statement. - Record changes made by before triggers and before-save flows do not use DML statements, which is one reason to prefer them for field updates on the same record.
- Roll-up summary recalculation and workflow field updates run inside the transaction, and the triggers they re-fire use the same budget.
- Limits for queries and DML are tracked per namespace, so a managed package gets its own count for those. CPU time and heap are shared by all code in the transaction.
Chunks of 200 share one transaction
When an Apex DML statement handles more than 200 records, Salesforce splits them into chunks of 200 and runs your trigger once per chunk. All chunks stay in the same transaction. Any query inside the trigger body runs once per chunk, so 1,000 records means 5 trigger runs and 5 times the queries.
Per-record work inside a loop multiplies the cost even more. A trigger with one query in a for loop and a chunk of 200 records uses 200 queries and fails.
A bulk-unsafe trigger and its fix
This version queries once for every contact:
trigger ContactAfterInsertBad on Contact (after insert) {
for (Contact c : Trigger.new) {
Account a = [SELECT Id, Description FROM Account WHERE Id = :c.AccountId];
a.Description = 'Has contacts';
update a;
}
}It spends one query and one DML statement per record. It also throws a null-related error when a contact has no account. The bulk-safe version collects Ids first, queries once, and runs a single DML statement:
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);
}
}
List<Account> accounts = [
SELECT Id, Description FROM Account WHERE Id IN :accountIds
];
for (Account a : accounts) {
a.Description = 'Has contacts';
}
update accounts;
}This uses one query and one DML statement per trigger run, no matter how many contacts are in the chunk. Updating the accounts can fire account triggers and flows, which spend from the same budget.
Watching the budget
The Limits class reports what the transaction has used so far. Logging it at the start and end of a trigger shows how much your code costs and how much was already gone when it started:
trigger AccountBudgetCheck on Account (before update) {
System.debug('Queries used: ' + Limits.getQueries()
+ ' of ' + Limits.getLimitQueries());
System.debug('DML statements used: ' + Limits.getDmlStatements()
+ ' of ' + Limits.getLimitDmlStatements());
System.debug('CPU ms used: ' + Limits.getCpuTime()
+ ' of ' + Limits.getLimitCpuTime());
}The LIMIT_USAGE_FOR_NS section of a debug log gives the same totals at the end of the transaction. The numbers there are cumulative for everything that ran, including flows.
Common mistakes
- Testing with one record. A trigger that passes a single-record test can fail when a data load sends 200 records.
- Counting only your own code. The remaining budget at the start of your trigger depends on every automation that ran before it.
- Adding recursion. A trigger that re-fires after a workflow field update runs its queries again. The guard from the recursion chapter protects the budget as well as the logic.
- Catching
LimitException. You cannot catch it. CheckLimitsvalues before expensive work, or move the work to an asynchronous job. - Heavy CPU in loops. Nested loops over large collections, string building, and complex formulas can use the 10-second CPU limit even with few queries. Use maps for lookups instead of nested loops.
Placing logic with limits in mind
Use before triggers or before-save flows for same-record changes, since they need no DML. Use one trigger per object that calls handler classes, so you can see and control the total queries. Keep queries outside loops and collect DML into lists. Treat the numbers above as the budget for the whole save, not for your piece of it.
Exercise
A trigger on Opportunity runs once per chunk of 200 records and contains one SOQL query outside any loop. An Apex class inserts 1,000 opportunities with a single insert statement. How many queries does this trigger use in the transaction, and is there a risk to the 100-query limit from other automation?
Show answer
The 1,000 records are split into 5 chunks, so the trigger runs 5 times and uses 5 queries. That is well within 100 by itself. Other triggers, flows, and code in the same transaction also count, and their per-chunk queries multiply the same way, so the total could still reach 100.
Exercise
Why does moving a field update from an after trigger to a before trigger reduce DML statement usage?
Show answer
A before trigger changes the incoming records directly, so no DML statement is needed. An after trigger must use an explicit update to change the same record, which uses a DML statement and can re-fire triggers and flows.