Sub topic 11
Governor limits and why bulk safety matters
This chapter assumes you know the Salesforce data model, can find objects and fields in Setup and the Object Manager, and can read a short Apex trigger or SOQL query. You do not need to write Apex to follow it. The limits apply to every automation tool in this tutorial, including Flow.
What governor limits are
Salesforce runs many customers on shared infrastructure (multitenancy). To stop one customer's code from using more than its share, the platform enforces governor limits. Each limit caps a resource inside one transaction, such as the number of queries or the CPU time.
A transaction is one unit of work that succeeds or fails together. Saving a record starts a transaction. Everything triggered by that save runs inside it: validation rules, before-save and after-save flows, Apex triggers and the records they update. These automations all draw on the same set of limits.
When a transaction exceeds a limit, the platform throws an exception that code cannot catch, and the whole transaction rolls back. Users see an error, and no changes are saved.
The limits that matter most
The values below are the standard synchronous limits. Check the current Salesforce documentation before relying on exact numbers, because they can change between releases.
| Limit (per synchronous transaction) | Value | Typical cause of hitting it |
|---|---|---|
| SOQL queries issued | 100 | A query inside a loop |
| Records returned by SOQL | 50,000 | Querying without a selective filter |
| DML statements issued | 150 | An update inside a loop |
| Records processed by DML | 10,000 | Cascading updates across many records |
| CPU time | 10,000 ms | Heavy loops, nested logic, many automations on one object |
| Heap size | 6 MB | Holding large collections in memory |
Asynchronous transactions, such as Queueable and Batch Apex, get higher values for some limits. For example, the CPU time is 60,000 ms and the heap is 12 MB. The limit for SOQL queries is still 200 for async, and DML statements are still 150.
Two points are easy to miss:
- The limits are per transaction, not per automation. If a flow runs 40 queries and a trigger runs 70 on the same save, the transaction has used 110 and fails.
- The limits count statements and records separately. One
updateof 200 records uses one DML statement and 200 DML rows.
What bulk means
Records rarely arrive one at a time. A data load, an integration, a list-view mass update, or a lead conversion can save up to 200 records in a single batch. Salesforce hands those records to your automation together, in one execution.
Bulk safe automation handles all of those records with a fixed number of queries and DML statements, no matter how many records there are. Bulk unsafe automation uses resources in proportion to the record count.
The classic failure is a query or DML statement inside a loop:
trigger ContactTrigger on Contact (after insert) {
for (Contact c : Trigger.new) {
// One query per contact. 101 contacts exceed the 100-query limit.
Account a = [SELECT Id, Name FROM Account WHERE Id = :c.AccountId];
a.Description = 'Has contacts';
update a; // One DML statement per contact.
}
}This works when a user saves one contact in the UI, which is why it often passes manual testing. It fails when a data load sends 200 contacts.
The bulk-safe version collects ids first, queries once, and updates once:
trigger ContactTrigger 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; // One query and one DML statement for any batch size.
}The pattern has three steps: collect, query once with IN, then change records in memory and save the list once.
Flow is bound by the same limits
Flow Builder hides the code, but the limits still apply. Each Get Records element is a query. Each Create Records, Update Records or Delete Records element is a DML statement.
Flow handles batches for you in many cases. A record-triggered flow receives the whole batch, and Salesforce bulkifies the elements that sit outside loops. The common mistake is to place a Get Records or Update Records element inside a Loop element. That reproduces the query-in-a-loop problem.
The bulk-safe flow pattern mirrors the Apex one:
- Run Get Records once, before the loop, to fetch all the related data.
- Inside the loop, only assign values to a collection variable.
- After the loop, run one Update Records element on the collection.
A before-save record-triggered flow that changes fields on the triggering record uses no DML statements at all. That is one reason it is the cheapest option for same-record updates.
Where limits hit in practice
Single automations are usually bulk safe on their own. Problems appear in combination:
- Cascading updates. An after-save flow updates a child record. That update fires the child's trigger, which updates another object, and so on. Each hop spends queries and DML from the same budget.
- Recursion. An automation updates a record, and that update re-fires the same automation. Without a guard, the transaction loops until a limit stops it.
- Many automations on one object. Five tools that each use 25 queries add up to 125.
- Unselective queries. A query on a large object with no indexed filter can scan more than 50,000 rows or time out.
The chapters on the order of execution and on coexisting automations cover how to control these combinations.
Handling the limits in code
You can inspect your consumption at runtime with the Limits class:
System.debug('Queries used: ' + Limits.getQueries() + ' of ' + Limits.getLimitQueries());
System.debug('DML statements used: ' + Limits.getDmlStatements() + ' of ' + Limits.getLimitDmlStatements());
System.debug('CPU time used: ' + Limits.getCpuTime() + ' of ' + Limits.getLimitCpuTime());Use these calls while developing to see where a transaction spends its budget. Do not build production logic that tries to dodge limits by checking them in the middle of a loop. Fix the structure of the code instead.
When the work is too large for one synchronous transaction, the solution is to move it to a separate transaction with fresh limits. Asynchronous Apex, covered in a later chapter, does this. A scheduled flow also runs its work in batches outside the user's save.
How limits shape tool choice
| Situation | Effect of limits | Better direction |
|---|---|---|
| Update fields on the saved record | Before-save flow needs no DML | Before-save flow or before trigger |
| Update related records for small batches | Fits within limits if bulkified | After-save flow |
| Heavy calculation across many records | CPU time may run out | Apex, possibly asynchronous |
| Process millions of records nightly | Synchronous limits are too small | Scheduled flow or Batch Apex |
| Callouts or slow work after a save | Blocks the user's transaction | Queueable Apex |
Common errors
- "Too many SOQL queries: 101". A query is inside a loop in Apex, or a Get Records element is inside a flow loop. Move it out and use a collection.
- "Too many DML statements: 151". An update or insert is inside a loop. Gather records into a list and save once.
- "Apex CPU time limit exceeded". Often caused by several automations on one object, or by nested loops. Remove duplicate automations first, then optimize the logic.
- "Too many DML rows: 10001". One transaction is changing too many records. Split the work into batches.
- Tests pass but the data load fails. The tests used one record. Add bulk tests.
Exercise
A trigger on Opportunity runs [SELECT Id FROM Account WHERE Id = :opp.AccountId] inside a for (Opportunity opp : Trigger.new) loop. It works when a sales rep edits one opportunity. A nightly integration then loads 150 opportunities and the load fails. What error do you expect, and how do you fix the trigger?
Show answer
The load fails with "Too many SOQL queries: 101", because the loop issues one query per opportunity and the synchronous limit is 100. Fix it by collecting the AccountId values into a Set inside the loop, running one query with WHERE Id IN :accountIds after the loop, and storing the results in a Map keyed by Id if you need to look up each account.
Exercise
A record-triggered flow has a Loop element over a collection of related Contacts. Inside the loop is an Update Records element that changes each contact. Why is this a problem, and what is the bulk-safe design?
Show answer
Each pass through the loop runs a separate DML statement, so a large collection can exceed the 150-statement limit and the other automations' usage is added on top. Use an Assignment element inside the loop to set the field values and add each contact to a collection variable. Then run one Update Records element on the collection after the loop ends.