Sub topic 5
Handling a List of Requests in One Pass
This chapter covers bulkification in invocable methods. It assumes you can write basic Apex, run SOQL, and know the governor limits for queries and DML. It also assumes you have seen the @InvocableMethod and @InvocableVariable rules from the earlier chapters.
Why the method receives a list
An invocable method always takes a List and returns a List. The platform may batch several invocations into one call. A flow can pass many records at once, and the runtime may group requests from more than one conversation turn or interview. Your method must treat the list as the unit of work.
Governor limits apply to the whole transaction, not to each request. A method that runs a query inside a loop uses one query per request. With 101 requests, it breaks the limit of 100 synchronous SOQL queries.
The pattern: collect, query, map, respond
Bulk-safe methods follow four steps. The GetOpenCasesAction class from this tutorial uses all of them.
- Collect the lookup keys from every request into a
Set<Id>. - Run one query with
WHERE AccountId IN :accountIds. - Group the results in a
Map<Id, List<Case>>. - Loop over the original requests and build one response for each.
Here is the collection step and the single query from that class:
Set<Id> accountIds = new Set<Id>();
for (Request r : requests) {
if (r.accountId != null) {
accountIds.add(r.accountId);
}
}
Map<Id, List<Case>> casesByAccount = new Map<Id, List<Case>>();
for (Case c : [
SELECT Id, CaseNumber, Subject, AccountId
FROM Case
WHERE AccountId IN :accountIds AND IsClosed = false
WITH USER_MODE
ORDER BY CreatedDate DESC
LIMIT 200
]) {
if (!casesByAccount.containsKey(c.AccountId)) {
casesByAccount.put(c.AccountId, new List<Case>());
}
casesByAccount.get(c.AccountId).add(c);
}The null check matters. A request with no accountId adds nothing to the set, and the query still runs once. If the set is empty, the query returns no rows and the method still returns a response for each request.
Keep the response list aligned
The platform matches responses to requests by position. The response at index 0 answers the request at index 0. You must return exactly one response per request, in the same order, even when a request has nothing to report.
List<Response> responses = new List<Response>();
for (Request r : requests) {
List<Case> cases = casesByAccount.containsKey(r.accountId)
? casesByAccount.get(r.accountId)
: new List<Case>();
// ... build the summary ...
responses.add(res);
}
return responses;Do not skip a request with continue unless you add a response first. A shorter list shifts every later answer onto the wrong request.
Per-request logic runs in memory
After the single query, the loop only reads from the map. Each request can have its own maxCases value, applied in memory:
Integer maxLines = (r.maxCases == null || r.maxCases < 1) ? 5 : r.maxCases;This keeps request-specific options cheap. Query once for the superset, then slice per request.
Common errors
| Mistake | Effect | Fix |
|---|---|---|
| SOQL or DML inside the request loop | `Too many SOQL queries: 101` or DML limit errors | Collect keys first, query once, then map |
| Returning fewer responses than requests | Answers attach to the wrong requests | Add a response for every request |
| Calling `map.get(key)` without a check | `NullPointerException` when no rows matched | Use `containsKey` or a default value |
| Assuming a single request | Failures only appear under load | Test with several requests |
Test with more than one request
A test with a single request cannot expose a per-record query. Pass at least two requests, ideally one with results and one without, and assert on order. The chapter on unit testing builds this out. For now, this check shows the idea:
@IsTest
static void keepsResponsesInRequestOrder() {
Account withCase = new Account(Name = 'Has Case');
Account noCase = new Account(Name = 'No Case');
insert new List<Account>{ withCase, noCase };
insert new Case(AccountId = withCase.Id, Subject = 'Login fails', Status = 'New');
GetOpenCasesAction.Request first = new GetOpenCasesAction.Request();
first.accountId = noCase.Id;
GetOpenCasesAction.Request second = new GetOpenCasesAction.Request();
second.accountId = withCase.Id;
List<GetOpenCasesAction.Response> results = GetOpenCasesAction.getOpenCases(
new List<GetOpenCasesAction.Request>{ first, second }
);
Assert.areEqual(2, results.size());
Assert.areEqual(0, results[0].caseCount);
Assert.areEqual(1, results[1].caseCount);
}Exercise
A teammate's invocable method contains for (Request r : requests) { r.cases = [SELECT Id FROM Case WHERE AccountId = :r.accountId]; }. Name the problem and describe the fix in terms of the four-step pattern.
Show answer
The query runs once per request, so a batch of 101 requests exceeds the 100 SOQL query limit. Collect all account Ids into a Set, run one query with AccountId IN :accountIds, group the cases in a Map keyed by AccountId, then loop over the requests and read each one's cases from the map. Return one response per request in the original order.
Exercise
Why must a method return a response for a request whose accountId is null?
Show answer
Responses are matched to requests by position. Skipping one makes the list shorter and shifts every later response onto the wrong request. Return a response with an empty or explanatory result instead.