Sub topic 5
Governor limits apply to both tools
This chapter assumes you know the basic Salesforce data model (objects, fields, records). It also assumes you have built a simple record-triggered flow and can read short Apex snippets with variables, loops, and collections.
Earlier chapters covered what Apex and Flow are and where each fits. This chapter covers a constraint they share. Both run on a multitenant platform, where many customers share the same servers. To keep one customer's runaway automation from starving the others, Salesforce enforces governor limits. A governor limit is a hard cap on the resources a single transaction may use.
The main point is that Flow does not avoid these limits. A flow and an Apex trigger on the same object draw from the same budget.
What a transaction is
A transaction is one unit of work that either fully commits or fully rolls back. Saving a record from the UI, an API call, or a batch of records from a data load each start a transaction. Everything triggered by that save runs inside it. That includes before-save flows, Apex triggers, after-save flows, validation rules, and any records those automations create or update.
Limits are counted per transaction, not per automation. If a record-triggered flow, an Apex trigger, and a second flow all fire on the same save, they add to one set of counters.
The limits you meet most often
These are the per-transaction limits for synchronous execution. Asynchronous Apex (queueable, batch, future) gets larger values for some of them. Check the current Salesforce documentation before relying on an exact number, because Salesforce can change them.
| Limit | Synchronous value | What consumes it |
|---|---|---|
| SOQL queries issued | 100 | Each SOQL query in Apex. Each Get Records element in a flow. |
| Records returned by SOQL | 50,000 | Rows returned across all queries. |
| DML statements | 150 | Each `insert`, `update`, `delete` in Apex. Each Create, Update, or Delete Records element in a flow. |
| Records processed by DML | 10,000 | Rows across all DML statements. |
| CPU time | 10,000 ms | Time spent in Apex and flow logic on the Salesforce server. |
| Heap size | 6 MB | Memory used by variables and collections. |
| Callouts | 100 | HTTP requests to external systems. |
Flow adds one limit of its own: a single flow interview can execute at most 2,000 elements at runtime. An interview is one running instance of a flow. This mostly catches loops that never end or that iterate over very large collections.
How flow elements map to limits
A flow is built from elements, and the elements that touch the database cost the same as their Apex equivalents.
- Get Records is a SOQL query. It uses 1 of the 100 queries.
- Create Records, Update Records, Delete Records are DML statements. Each uses 1 of the 150.
- Action elements that call Apex, send email, or post to Chatter consume whatever those actions consume. An Apex action can spend queries, DML, and CPU of its own.
- Subflows run inside the same transaction, so everything they use is added to the caller's totals.
The mapping explains why the "no code" label can mislead. A flow with a Get Records element inside a loop issues one query per loop pass. That is the same mistake as writing a SOQL query inside a for loop in Apex, and it fails the same way.
The loop mistake in both tools
The next two Apex snippets show the pattern. The first queries once for each record. The second queries once for all records.
// Anti-pattern: one query per contact. 101 contacts means 101 queries.
List<Contact> contacts = [SELECT Id, AccountId FROM Contact LIMIT 150];
for (Contact c : contacts) {
Account a = [SELECT Id, Name FROM Account WHERE Id = :c.AccountId];
System.debug(a.Name);
}On the 101st pass this code throws System.LimitException: Too many SOQL queries: 101.
// Better: collect the Ids first, then query once.
List<Contact> contacts = [SELECT Id, AccountId FROM Contact LIMIT 150];
Set<Id> accountIds = new Set<Id>();
for (Contact c : contacts) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, Name FROM Account WHERE Id IN :accountIds]
);
for (Contact c : contacts) {
Account a = accountsById.get(c.AccountId);
if (a != null) {
System.debug(a.Name);
}
}The flow version of the fix is the same idea. Run Get Records once before the loop and store the result in a collection variable. Inside the loop, only assign values to a record variable and add it to a collection. After the loop, run a single Update Records element on the whole collection. A later chapter covers bulk-safe design in detail.
Limits are shared, so order and neighbors matter
Suppose your Apex trigger uses 40 queries and a flow on the same object uses 70. Each looks acceptable on its own, but the transaction needs 110 queries and fails. The error can appear in either automation, depending on which one runs when the counter passes 100. The automation that throws the error is often not the one that caused the problem.
Two consequences follow.
- Budget per object, not per tool. When you add automation to an object, check what already fires there, whether it is flows, triggers, or packaged code from an app you installed.
- Test with realistic volume. A flow that works when you save one record in the UI may fail when a data load saves 200 in one batch. Record-triggered automation processes records in chunks of up to 200 per transaction, and all 200 share one set of limits.
Reading limit usage while Apex runs
Apex has a Limits class that reports consumption. It is useful for learning where the budget goes. Run this in the Developer Console under Debug > Open Execute Anonymous Apex.
System.debug('Queries before: ' + Limits.getQueries() + ' of ' + Limits.getLimitQueries());
System.debug('DML before: ' + Limits.getDmlStatements() + ' of ' + Limits.getLimitDmlStatements());
List<Account> accounts = [SELECT Id, Name FROM Account LIMIT 5];
for (Account a : accounts) {
a.Description = 'Checked ' + System.now();
}
update accounts;
System.debug('Queries after: ' + Limits.getQueries() + ' of ' + Limits.getLimitQueries());
System.debug('DML after: ' + Limits.getDmlStatements() + ' of ' + Limits.getLimitDmlStatements());
System.debug('CPU ms: ' + Limits.getCpuTime() + ' of ' + Limits.getLimitCpuTime());The "after" lines show one more query and one more DML statement than the "before" lines, whatever the number of records. If you run this in an org with no accounts, the update is skipped. Add at least one account first to see the DML counter change.
This code also shows why the counters count statements and not rows. Updating 5 accounts in a list is 1 DML statement. Updating them one at a time in a loop would be 5.
For flows, you cannot call Limits directly. You look at the debug log instead. Set a debug log for your user, save a record that fires the flow, and open the log. Search for CUMULATIVE_LIMIT_USAGE. That section lists how many queries, DML statements, and CPU milliseconds the whole transaction used, grouped by namespace. Lines such as FLOW_ELEMENT_BEGIN show which flow elements ran and in what order.
What happens when a limit is hit
Limit failures behave differently from ordinary errors.
- Apex: A
LimitExceptioncannot be caught. Atry/catchblock does not stop it, so the transaction ends and all changes in it roll back. - Flow: A fault path on an element handles errors such as a failed validation or a missing required field. It does not recover from a governor limit. The interview stops and the transaction rolls back.
- The user sees an error message. For record-triggered automation, the save fails and no records are written. For flows, the person who owns the flow may get a flow error email.
Limits that differ by execution context
The same code gets different budgets depending on how it runs.
- Asynchronous Apex (queueable, batch, scheduled, future) has a larger CPU time limit of 60,000 ms and a larger heap of 12 MB. Each batch execute call is its own transaction with a fresh budget.
- Scheduled-path and asynchronous flow paths run in their own transaction after the triggering save commits, so they start with a fresh set of counters.
- Autolaunched flows called from Apex run in the caller's transaction and share its budget.
This is one reason Apex becomes the better tool for very large jobs. Batch Apex can process millions of records by splitting them into many transactions, and a single flow interview has no equivalent when you need explicit control over chunk size. A later chapter on the decision framework builds on this.
Common mistakes
- Assuming Flow is exempt from limits because it has no code.
- Putting Get Records or Update Records inside a loop.
- Counting only your own automation and forgetting packages or older flows on the same object.
- Testing a record-triggered flow with a single record, then loading data in batches of 200.
- Wrapping Apex in
try/catchand expecting it to handle a limit error.
Exercise
A record-triggered flow on Opportunity has a loop over 150 related Contacts. Inside the loop, a Get Records element looks up the Account for each Contact, and an Update Records element saves each Contact. Which limits does this break, and how would you fix it?
Show answer
The flow runs 150 queries and 150 DML statements for one interview, which exceeds the limits of 100 SOQL queries and 150 DML statements (the 101st Get Records fails, and the 151st Update Records would too). Fix it by moving Get Records before the loop and collecting the results. Inside the loop, only assign values to a record variable and add it to a collection. After the loop, run one Update Records element on the whole collection. This uses 1 query and 1 DML statement however many Contacts there are.
Exercise
An Apex trigger on Case uses 60 SOQL queries per transaction. A new flow on Case uses 50. Neither is above 100 on its own. What happens when both fire on the same save, and why can you not fix it with a try/catch block?
Show answer
Together they need 110 queries, so the transaction fails with "Too many SOQL queries: 101" and everything rolls back. Limits are counted per transaction, not per automation, so the totals are added. A LimitException cannot be caught, so try/catch does not help. The fix is to reduce the queries in one or both automations, for example by moving the queries out of loops or merging the two into one automation.
Exercise
Where in a debug log do you find the total queries and DML statements used by a transaction that included a flow?
Show answer
In the CUMULATIVELIMITUSAGE section of the debug log, which lists usage for each limit such as SOQL queries, DML statements, and CPU time. Individual flow elements appear as FLOWELEMENTBEGIN lines, which show what ran and in what order.