Sub topic 6
Handling many flow interviews in one call
This chapter assumes you can write basic Apex (classes, collections, SOQL, DML) and that you know how record-triggered flows and flow variables work. You should also know the governor limits for SOQL queries and DML statements.
Why an invocable method receives a list
A flow interview is one running instance of a flow. When a user saves one record, one interview runs. When a data load, an API call, or a bulk update changes 200 records, Salesforce starts one interview per record. It then groups the interviews that reach the same Apex action and calls your method once, passing one list element for each interview.
This is why every invocable method takes a List parameter, even when you only picture a single record. The list is the batch of interviews, not a collection that your flow built.
- Each element of the input list comes from one interview.
- A record-triggered flow can pass up to 200 elements, which matches the trigger batch size.
- Scheduled flows and bulk API operations can also send many elements in one call.
- A screen flow usually sends a list of one.
- All interviews in a batch share one transaction and one set of governor limits.
The last point causes most bulk bugs. A query inside a loop that costs one SOQL query for a single record costs 200 queries for a batch. The limit is 100 queries per synchronous transaction, and the flow's own queries count against it too.
The ordering contract
The runtime does not match results to interviews by key. It matches them by position. For a method that returns a list, you must follow two rules:
- Return exactly one result for each request.
- Return the results in the same order as the requests.
If you break either rule, interview B can receive the result that belongs to interview C. The flow does not know this happened. The result is wrong data that looks valid, which is worse than an error. This is why the AccountTaskCreator example in the spine builds its result list by walking the save results in order.
A method that returns void has no results to order. It still receives the full batch, so it must still be bulk-safe.
The bulk pattern: collect, act once, map back
Almost every bulk-safe invocable method follows the same four steps.
- Loop over the requests to collect IDs and values into sets, maps, or lists.
- Run one query for all the IDs, or build all the records for one DML statement.
- Run the query or the DML once, outside any loop.
- Loop over the requests again and build one result for each, using a map or an index to find the right data.
Here is a read-only example that follows this pattern.
public with sharing class AccountOwnerLookup {
public class Request {
@InvocableVariable(label='Account Id' required=true)
public Id accountId;
}
public class Result {
@InvocableVariable(label='Owner Id')
public Id ownerId;
@InvocableVariable(label='Account Found')
public Boolean found;
}
@InvocableMethod(
label='Get Account Owners'
description='Returns the owner of each account, one result per request.'
category='Account'
)
public static List<Result> getOwners(List<Request> requests) {
// Step 1: collect the IDs
Set<Id> accountIds = new Set<Id>();
for (Request req : requests) {
if (req.accountId != null) {
accountIds.add(req.accountId);
}
}
// Steps 2 and 3: one query for the whole batch
Map<Id, Account> accountsById = new Map<Id, Account>(
[SELECT Id, OwnerId FROM Account WHERE Id IN :accountIds]
);
// Step 4: one result per request, in request order
List<Result> results = new List<Result>();
for (Request req : requests) {
Result res = new Result();
Account acc = req.accountId == null ? null : accountsById.get(req.accountId);
res.found = (acc != null);
res.ownerId = res.found ? acc.OwnerId : null;
results.add(res);
}
return results;
}
}Three details in this code are easy to miss.
- Duplicates. Two interviews can pass the same account ID. A
Setremoves the duplicate from the query. The second loop still emits two results, because there are two requests. - Missing records. If an ID matches no account, the method still returns a result, with
foundset to false. It does not skip the request. - Null inputs. A flow can pass a null if a variable is empty. The method checks for null instead of failing the whole batch.
Query pattern: loop versus map
| Task | Unsafe in a batch | Bulk-safe |
|---|---|---|
| Look up a related record | `[SELECT ... WHERE Id = :req.accountId]` inside the loop | One `WHERE Id IN :ids` query, then `Map.get()` |
| Insert records | `insert task;` inside the loop | Add to a `List`, then one `Database.insert` |
| Update records | `update acc;` inside the loop | Collect changed records, then one `update` |
| Check for duplicates | A query for each request | One query, then a `Set` of existing keys |
Keeping results aligned when you skip requests
The simplest case is one DML record for each request. The save results line up with the requests with no extra work. Real methods often skip requests that are invalid. If you build the DML list only from valid requests, its indexes no longer match the request indexes.
The fix is to create every result first, remember which request each DML record came from, and write each outcome back to the right result.
public with sharing class CaseCommentCreator {
public class Request {
@InvocableVariable(label='Case Id' required=true)
public Id caseId;
@InvocableVariable(label='Comment Text' required=true)
public String body;
}
public class Result {
@InvocableVariable(label='Comment Id')
public Id commentId;
@InvocableVariable(label='Is Success')
public Boolean isSuccess;
@InvocableVariable(label='Error Message')
public String errorMessage;
}
@InvocableMethod(
label='Add Case Comments'
description='Adds one comment per request and returns one result per request.'
category='Case'
)
public static List<Result> addComments(List<Request> requests) {
List<Result> results = new List<Result>();
List<CaseComment> comments = new List<CaseComment>();
List<Integer> requestIndexes = new List<Integer>();
for (Integer i = 0; i < requests.size(); i++) {
Request req = requests[i];
Result res = new Result();
res.isSuccess = false;
results.add(res); // a result exists for every request
if (req.caseId == null || String.isBlank(req.body)) {
res.errorMessage = 'Case Id and comment text are both required.';
continue; // skipped: nothing is added to the DML list
}
comments.add(new CaseComment(ParentId = req.caseId, CommentBody = req.body));
requestIndexes.add(i); // remember which request this comment came from
}
List<Database.SaveResult> saveResults = Database.insert(comments, false);
for (Integer j = 0; j < saveResults.size(); j++) {
Result res = results[requestIndexes[j]];
if (saveResults[j].isSuccess()) {
res.isSuccess = true;
res.commentId = saveResults[j].getId();
} else {
res.errorMessage = saveResults[j].getErrors()[0].getMessage();
}
}
return results;
}
}The requestIndexes list is the key. Position j in the DML list belongs to request requestIndexes[j]. Database.insert returns save results in the same order as the list you passed in, so this mapping holds.
The second argument, false, turns on partial success. One bad record does not roll back the others, and each failure shows up in its own result. Chapter on error handling covers when to prefer this over throwing an exception.
Shared limits across the batch
All 200 interviews run in the same transaction as the record save that triggered them. The transaction also includes triggers, other flows, and workflow on the same records. Your method's queries and DML add to the same counters.
- Aim for a constant number of queries and DML statements per call, whatever the batch size.
- Take a query count of one or two as normal, and treat a count that grows with the list size as a defect.
- Keep memory in mind. A map of 200 full records is fine, but select only the fields you need.
Common errors
- Returning fewer results than requests. This usually happens when a
continueskips theresults.addcall. Add the result before any early exit. - Sorting or reordering the output. Building results from a
MaporSetiteration loses request order. Always build the result list by looping overrequests. - Treating a request as unique. Two requests can hold the same ID, so do not use the ID as the key for a result.
- Using a static variable to remember one request. The method runs once for the whole batch, so per-interview state belongs in the request and result objects.
- Assuming a single record in a screen flow. The same method is later reused from a record-triggered flow, and it breaks.
Exercise
A method receives 5 requests. Requests 2 and 4 have a null accountId, so you skip them when building the List<Task> for DML. The DML list has 3 tasks. You then loop over the 3 save results and add one Result for each. What goes wrong, and how do you fix it?
Show answer
The method returns 3 results for 5 requests, so the ordering contract is broken. Result 2 (which belongs to request 3) is handed to interview 2, and interviews 4 and 5 get nothing. To fix it, create a Result for every request in the first loop, with an error message for the skipped ones. Record each DML record's request index in a List<Integer>. After Database.insert, use that list to write each save result into results[requestIndexes[j]].