Sub topic 5
Handling a list of requests in one pass
This chapter assumes you can write basic Apex with collections and SOQL. It also assumes you have read the earlier chapters on @InvocableMethod and on @InvocableVariable request and response types. Here you will learn why an invocable method takes a list, what the platform expects you to return, and how to write the method so it uses a fixed number of queries and DML statements.
Why the method receives a list
An invocable method always takes a List and returns a List. That rule exists because the platform can batch calls. A Flow that runs for 50 records in one transaction can reach your method once with 50 requests. Agentforce usually sends one request per call, because the agent is handling one conversation turn. Do not rely on that. The same class can be called from a Flow, from another Apex class, or from a test with many items, and it must behave correctly each time.
The contract has two parts:
- The input is a list of request objects, one for each call.
- The output is a list of response objects. It must have the same size and the same order as the input. The platform pairs each response with its request by position.
If you return fewer responses than requests, or return them in a different order, the caller gets the wrong data or an error. There is no key that lets the platform re-match them for you.
The cost of per-request work
The most common mistake is to write the method as if it handled one request, then wrap that code in a loop.
// Anti-pattern: one query for each request
public static List<Response> getOpenCases(List<Request> requests) {
List<Response> responses = new List<Response>();
for (Request r : requests) {
List<Case> cases = [
SELECT Id, CaseNumber, Subject
FROM Case
WHERE AccountId = :r.accountId AND IsClosed = false
];
// build a response from cases ...
}
return responses;
}This works in a test with one request. With 101 requests in one transaction it fails with System.LimitException: Too many SOQL queries: 101. The limit is 100 synchronous SOQL queries per transaction. DML has a similar limit of 150 statements. Because the failure depends on the size of the batch, it often appears only in production.
The pattern: collect, query once, group, respond
The method from the topic's main example follows four steps. Look at each one in turn.
- Collect keys. Loop over the requests and add each key, here
accountId, to aSet<Id>. A set removes duplicates, so two requests for the same account produce one key. Skip null keys, becauseIN :accountIdswith a null in the set is wasteful and usually unintended. - Query once. Run one SOQL statement with
WHERE AccountId IN :accountIds. - Group the results. Put rows into a
Map<Id, List<Case>>keyed by the same field you collected. CheckcontainsKeybefore you add to a list, as the example does. - Respond in order. Loop over the original
requestslist. For each one, look up its rows in the map and build a response. Add the response to the output list in the same pass.
Step 4 is where order is preserved. Never loop over the map to build responses, because map iteration order is not tied to the order of the input list. Always loop over the input.
List<Response> responses = new List<Response>();
for (Request r : requests) {
List<Case> cases = casesByAccount.containsKey(r.accountId)
? casesByAccount.get(r.accountId)
: new List<Case>();
Response res = new Response();
res.caseCount = cases.size();
// ... fill the rest of the response
responses.add(res);
}
return responses;Every request gets a response, including requests with a null key or with no matching rows. A request with no data still needs a response object that says so.
Duplicates and shared results
Two requests with the same accountId each get their own response. Both read from the same list in the map. That is safe as long as you do not change the shared list or the records inside it. If one request needs a trimmed version of the list, copy what you need into a new list or string, as the example does with lines. Do not remove items from the list in the map.
A limit that is easy to get wrong
The example query ends with LIMIT 200. That limit applies to the whole result set, not to each account. If 10 accounts have 50 open cases each, the query returns only 200 of the 500 rows. Some accounts will show too few cases, or none, and caseCount will be wrong for them. The cap is a safety net against the 50,000-row query limit. It is not a per-request cap.
You have three ways to handle this:
- Keep the
LIMITand accept that the count is approximate. If you do, say so in the description of the output field. - Use an aggregate query (
SELECT AccountId, COUNT(Id) ... GROUP BY AccountId) for exact counts, and a separate limited query for the sample lines. - Document that the action is designed for one account at a time, which is the normal Agentforce case.
The choice depends on how the action is used. For an agent-only action, the first option is usually acceptable. For one that Flows also call in bulk, use the aggregate query.
Bulk DML with a matching response
Writes follow the same idea, with one extra problem. When you insert a list of records, some may succeed and some may fail, and you must still return one response for each request. You also must not insert records for requests that failed validation, so the positions in the insert list no longer match the positions in the request list. You need to keep track of which request each record came from.
public with sharing class CreateFollowUpTaskAction {
public class Request {
@InvocableVariable(
label='Case Id'
description='The Salesforce Id of the case that needs a follow-up task'
required=true
)
public Id caseId;
@InvocableVariable(
label='Task Subject'
description='A short description of the follow-up work'
required=true
)
public String subject;
}
public class Response {
@InvocableVariable(
label='Task Id'
description='The Id of the created task, empty if creation failed'
)
public Id taskId;
@InvocableVariable(
label='Message'
description='A plain-language result, including the reason if the task was not created'
)
public String message;
}
@InvocableMethod(
label='Create Follow-Up Task'
description='Creates a follow-up task on a case, due tomorrow'
category='Service'
)
public static List<Response> createTasks(List<Request> requests) {
List<Response> responses = new List<Response>();
List<Task> toInsert = new List<Task>();
List<Integer> requestIndexes = new List<Integer>();
for (Integer i = 0; i < requests.size(); i++) {
Request r = requests[i];
Response res = new Response();
responses.add(res);
if (r.caseId == null || String.isBlank(r.subject)) {
res.message = 'A case Id and a subject are both required.';
continue;
}
toInsert.add(new Task(
WhatId = r.caseId,
Subject = r.subject,
ActivityDate = Date.today().addDays(1)
));
requestIndexes.add(i);
}
if (toInsert.isEmpty()) {
return responses;
}
try {
List<Database.SaveResult> results =
Database.insert(toInsert, false, AccessLevel.USER_MODE);
for (Integer j = 0; j < results.size(); j++) {
Response res = responses[requestIndexes[j]];
if (results[j].isSuccess()) {
res.taskId = results[j].getId();
res.message = 'The follow-up task was created.';
} else {
res.message = 'The task could not be created: '
+ results[j].getErrors()[0].getMessage();
}
}
} catch (DmlException e) {
for (Integer idx : requestIndexes) {
responses[idx].message = 'The task could not be created: ' + e.getMessage();
}
}
return responses;
}
}Three details make this work:
- The method adds a
Responseto the output list at the top of every loop pass. That fixes the output size and order before any logic can skip a request. requestIndexesrecords which request produced each task, soresults[j]maps back toresponses[requestIndexes[j]].Database.insertwithallOrNoneset tofalselets valid records save when others fail. The method then reports each failure in its own response.
Which behavior you want depends on the action. If the requests are independent, as they are here, partial success is better. If they must succeed or fail together, use true and handle the single exception.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Too many SOQL queries: 101` | A query inside the loop over requests | Collect keys, query once, group with a map |
| Responses appear on the wrong request | Built by looping over the map or the query results | Loop over the input list and add one response each time |
| `ListException: List index out of bounds` in the caller | Fewer responses than requests, often from `continue` before `responses.add` | Add the response first, then decide whether to skip |
| Counts too low for some accounts | One `LIMIT` shared across all keys | Use an aggregate query or document the cap |
| Null-pointer error on a missing record | `map.get(key).add(...)` without `containsKey` | Check `containsKey` and create the list first |
| One bad request fails all the others | Unhandled exception thrown from inside the loop | Validate each request, and use partial-success DML |
Testing the bulk path
The unit tests in this tutorial call the method with a single request. A bulk test should also send many requests, and it should check order. Create several accounts, build requests in a deliberate order, and assert on each response by index. Also include a request with a null accountId and one with an account that has no cases. A test that passes 150 requests with real queries will fail on a per-request query, which is the purpose of the test.
Exercise
A teammate rewrites getOpenCases so that it loops over casesByAccount.keySet() and adds one response for each key. Unit tests with one request still pass. Give two ways this breaks in real use.
Show answer
First, the output no longer matches the input. Requests with no open cases have no key in the map, so they get no response, and the list is shorter than the request list. Second, map iteration order is not the request order, so the responses are paired with the wrong requests. Duplicate requests for one account also collapse into a single response. The fix is to loop over requests and look each key up in the map.
Exercise
In CreateFollowUpTaskAction, 5 requests arrive. Request 2 (index 1) has a blank subject, and the other four are valid. The insert is run with allOrNone set to false, and the record for request 4 (index 3) fails a validation rule. What are the contents of requestIndexes, and which responses carry an error message?
Show answer
requestIndexes is [0, 2, 3, 4] because index 1 was skipped. toInsert has four records, so results has four entries. The failed record is entry 2 in results, which maps to responses[requestIndexes[2]], that is responses[3]. Responses at index 1 (blank subject) and index 3 (validation failure) carry error messages. Responses at indexes 0, 2, and 4 carry a task Id and a success message.