Sub topic 10
Transaction Context and Governor Limits
This chapter assumes you know basic Apex (classes, collections, SOQL, DML), the Flow Builder concepts of record-triggered and screen flows, and the idea that Apex enforces governor limits. It builds on the request and response classes and the bulkification rules from earlier chapters. Here you learn what an invocable method shares with the flow that calls it, and how that sharing affects limits.
The method runs inside the flow's transaction
An invocable method does not get its own transaction. When a flow reaches an Apex action, the method runs in the same database transaction as the flow interview. The interview is one running instance of a flow. Everything that happened earlier in that transaction counts against the method: the flow's own queries and DML, triggers, and other automation.
Three consequences follow:
- Limits are shared. The method does not get a fresh budget of 100 SOQL queries. It gets whatever is left after everything else in the transaction has run.
- Rollback is shared. If the transaction fails with an unhandled error, all of its uncommitted changes roll back. That includes records the flow created before it called your method.
- Side effects cascade. DML inside your method fires triggers and record-triggered flows on the affected objects, and they run in the same transaction too.
How batching produces the list your method receives
Flow groups interviews so that your method is called once per batch, not once per record. If a data load saves 200 accounts and an after-save flow runs for each, the flow runtime collects the 200 requests for the same Apex action and calls the method one time with a list of 200 items.
This is why the method signature takes a List. The list is the unit of work for the transaction, so the whole transaction's limits are spent per list, not per record. A method that queries or runs DML per list item scales with the number of records saved and eventually fails.
The batch size depends on the context:
| Context | What the list usually contains |
|---|---|
| After-save record-triggered flow | Up to 200 records per trigger batch, one request each |
| Screen flow | Usually one request, because one user runs one interview |
| Autolaunched flow started from Apex or a scheduled path | As many interviews as the caller started in the transaction |
| Flow with the action inside a loop | One request per loop iteration, and each call is separate unless the flow runtime groups them |
The last row matters. Calling an Apex action inside a flow Loop element works, but each pass is a separate call with a list of one. Prefer collecting values in the loop, then calling the action once after the loop with a collection input. Your method then receives one request that holds the whole collection, or you pass the collection through a wrapper field.
Before-save record-triggered flows cannot call Apex actions. Only after-save flows can.
Limits that matter most
The limits depend on whether the transaction is synchronous or asynchronous. Most flow work is synchronous.
| Limit | Synchronous | Asynchronous |
|---|---|---|
| SOQL queries issued | 100 | 200 |
| Records returned by SOQL | 50,000 | 50,000 |
| DML statements | 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 | 100 | 100 |
These are per transaction, not per method. In practice, the numbers that cause trouble are SOQL queries, DML statements, and CPU time. A flow with several Get Records elements, a trigger on the object, and your method all draw from the same 100 queries.
The flow also has limits of its own. For example, a single interview can execute only a fixed number of elements at runtime, and a loop that runs thousands of iterations can hit it. Those limits are separate from Apex limits.
Writing a method that spends limits per list
The pattern is the same every time: collect keys from the whole list, run one query, keep results in a map, then build the output in input order.
public with sharing class OpenOpportunityCounter {
public class Request {
@InvocableVariable(label='Account Id' required=true)
public Id accountId;
}
public class Result {
@InvocableVariable(label='Open Opportunity Count')
public Integer openCount;
}
@InvocableMethod(
label='Count Open Opportunities'
description='Returns the number of open opportunities for each account, in request order.'
)
public static List<Result> countOpen(List<Request> requests) {
Set<Id> accountIds = new Set<Id>();
for (Request req : requests) {
if (req.accountId != null) {
accountIds.add(req.accountId);
}
}
Map<Id, Integer> countsByAccount = new Map<Id, Integer>();
for (AggregateResult ar : [
SELECT AccountId acc, COUNT(Id) total
FROM Opportunity
WHERE AccountId IN :accountIds AND IsClosed = false
GROUP BY AccountId
]) {
countsByAccount.put((Id) ar.get('acc'), (Integer) ar.get('total'));
}
List<Result> results = new List<Result>();
for (Request req : requests) {
Result res = new Result();
res.openCount = countsByAccount.containsKey(req.accountId)
? countsByAccount.get(req.accountId)
: 0;
results.add(res);
}
return results;
}
}Whether the list holds 1 request or 200, the method issues exactly one SOQL query. The aggregate query also returns at most one row per account, so it uses far fewer of the 50,000 query rows than a query over every opportunity would.
Compare the version that fails under load:
// Anti-pattern: one query per request
for (Request req : requests) {
Integer total = [SELECT COUNT() FROM Opportunity
WHERE AccountId = :req.accountId AND IsClosed = false];
// ...
}With 101 requests in one transaction, this throws a System.LimitException on the 101st query, and nothing in the flow can recover.
Governor limit errors cannot be handled
Apex try/catch cannot catch a System.LimitException. When a limit is exceeded, Salesforce ends the transaction and rolls it back. Do not design around catching it, and do not assume a flow's fault connector gives you a clean recovery path for it. Treat limit safety as something you build into the code through bulkification.
Ordinary exceptions are different. An unhandled DmlException or a custom exception you throw is reported to the flow, and the error handling chapter covers how that reaches the fault path.
Watching your consumption
The Limits class reports how much of each budget the current transaction has used. It helps when you need to measure what your method costs, or what remains when it starts.
public with sharing class LimitSnapshot {
public static String describe(String label) {
return label
+ ' | SOQL ' + Limits.getQueries() + '/' + Limits.getLimitQueries()
+ ' | DML ' + Limits.getDmlStatements() + '/' + Limits.getLimitDmlStatements()
+ ' | CPU ' + Limits.getCpuTime() + '/' + Limits.getLimitCpuTime() + ' ms';
}
}Call System.debug(LimitSnapshot.describe('start')) at the top of your invocable method and again before the return. The first line shows what the flow and triggers already used. The difference between the two lines is your method's own cost.
Transaction boundaries in different flow types
Where the transaction starts and ends depends on how the flow was launched.
- Record-triggered flows run inside the transaction of the save that triggered them. Your method runs between that save's own triggers and its commit.
- Screen flows run a transaction from one screen to the next. When the flow reaches a screen, the pending work commits. When the user clicks Next, a new transaction starts and runs until the next screen or the end. Each transaction has a fresh limit budget.
- Flows with a Pause element or a scheduled path commit before pausing and start a new transaction when they resume.
Transaction boundaries also decide whether callouts are allowed. A callout is an HTTP request to an external system. Apex refuses a callout in a transaction that has uncommitted DML, and it throws a CalloutException with the message "You have uncommitted work pending." So a screen flow that creates a record and then calls a callout action in the same transaction fails. Placing the callout action after a screen, which commits the earlier work, avoids it. Record-triggered flows have their own restrictions on synchronous callouts, which the callouts chapter covers in full.
Testing limit behavior
Apex tests give you a fresh set of limits between Test.startTest() and Test.stopTest(), so setup work does not count against the code you measure. Use that to prove your method is bulk-safe: call it with 200 requests and check query and DML counts.
@IsTest
private class OpenOpportunityCounterTest {
@IsTest
static void usesOneQueryForTwoHundredRequests() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Limit Test ' + i));
}
insert accounts;
List<OpenOpportunityCounter.Request> requests =
new List<OpenOpportunityCounter.Request>();
for (Account acc : accounts) {
OpenOpportunityCounter.Request req = new OpenOpportunityCounter.Request();
req.accountId = acc.Id;
requests.add(req);
}
Test.startTest();
List<OpenOpportunityCounter.Result> results =
OpenOpportunityCounter.countOpen(requests);
Integer queriesUsed = Limits.getQueries();
Test.stopTest();
Assert.areEqual(200, results.size(), 'One result per request');
Assert.areEqual(1, queriesUsed, 'The method should issue a single query');
Assert.areEqual(0, results[0].openCount, 'No opportunities exist yet');
}
}Reading Limits.getQueries() inside the start and stop block measures only the code you called. A per-record query would make this test fail with a limit exception, which is the point.
Common mistakes
- Querying or running DML inside the request loop. Move it outside the loop and use a
Setof keys and aMapof results. - Ignoring what the flow already used. Your method shares the budget with every Get Records element and trigger in the transaction.
- Expecting
try/catchto rescue a limit failure. It cannot. Prevent the failure by bulkifying. - Calling the action once per record from a flow loop. Collect values in the loop and call the action once afterward.
- Doing a callout after DML in the same transaction. Move the callout to a new transaction, as the callouts chapter explains.
- Testing only one request. A single-request test cannot reveal a per-record query.
Exercise
A record-triggered after-save flow on Account calls your invocable method. A user imports 200 accounts in one batch. Your method runs one SOQL query for each request in its list. The flow also has three Get Records elements and the Account has a trigger that runs one query. What happens, and how do you fix the method?
Show answer
The method receives one list of 200 requests and runs 200 queries, which exceeds the synchronous limit of 100 queries. Salesforce throws a System.LimitException, which try/catch cannot handle, and the whole transaction rolls back, including the 200 account saves. The flow's own queries and the trigger's query make it worse because they share the same budget. Fix it by collecting the account Ids into a Set, running one query with WHERE Id IN :ids (or an aggregate query), storing results in a Map, and building one result per request in input order.
Exercise
A screen flow creates a Case with a Create Records element and then, on the same screen transition, calls an Apex action that makes an HTTP callout. The action fails with "You have uncommitted work pending." Why does this happen, and what is one way to restructure the flow?
Show answer
The Case insert is uncommitted DML in the current transaction, and Apex does not allow a callout while uncommitted work is pending. A screen flow commits its work when it reaches a screen, so you can restructure the flow so that the callout action runs in the transaction that starts after a screen. Another approach is to run the callout in a separate transaction, for example from an asynchronous path, and the callouts chapter covers those options.
Exercise
Why does a test that calls an invocable method with a single request not prove the method is safe for limits? What should the test do instead?
Show answer
A single request runs at most one iteration of any loop, so a per-record query or DML statement stays far below the limits. A full trigger batch has 200 records, so the test should call the method with 200 requests between Test.startTest() and Test.stopTest(), then assert the result count and check Limits.getQueries() and Limits.getDmlStatements() against the numbers you expect.