Sub topic 13
Governor limits and bulk-friendly endpoints
This chapter assumes you can write SOQL and DML, and that you have built a basic @RestResource class with @HttpGet and @HttpPost methods. It covers how governor limits apply to Apex REST and how to design endpoints that stay inside them.
How limits apply to a REST request
Each call to an Apex REST endpoint runs in its own transaction. The usual synchronous Apex limits apply to that transaction. Two of them matter most here:
| Limit | Synchronous value |
|---|---|
| SOQL queries | 100 |
| DML statements | 150 |
| Rows returned by SOQL | 50,000 |
| Records processed by DML | 10,000 |
| CPU time | 10,000 ms |
| Heap size | 6 MB |
Heap is the limit REST services hit most often, because the request body and the response body are both held in memory. A large JSON payload can exhaust the heap before your logic runs. Salesforce also caps request and response bodies for Apex REST at about 6 MB, so a large payload fails at the API layer.
Separately from governor limits, your org has a daily API request allocation. Each call to your service counts against it. Many small calls cost more of that allocation than one batched call.
The one-record-per-call trap
The first @HttpPost you write usually handles one record. A client that must load 500 records then makes 500 calls. That is slow, spends API requests, and risks concurrency problems.
Allow the client to send a list instead. Apex binds a JSON array to a List parameter, so the handler can receive many records at once.
@RestResource(urlMapping='/v1/AccountBatch/*')
global with sharing class AccountBatchService {
global class AccountInput {
global String name;
global String industry;
}
global class ItemResult {
global Integer index;
global Id id;
global Boolean success;
global String message;
}
@HttpPost
global static List<ItemResult> createAccounts(List<AccountInput> accounts) {
RestResponse res = RestContext.response;
List<ItemResult> results = new List<ItemResult>();
if (accounts == null || accounts.isEmpty()) {
res.statusCode = 400;
return results;
}
if (accounts.size() > 200) {
res.statusCode = 413;
return results;
}
List<Account> toInsert = new List<Account>();
for (AccountInput input : accounts) {
toInsert.add(new Account(Name = input.name, Industry = input.industry));
}
List<Database.SaveResult> saves = Database.insert(toInsert, false, AccessLevel.USER_MODE);
for (Integer i = 0; i < saves.size(); i++) {
ItemResult item = new ItemResult();
item.index = i;
item.success = saves[i].isSuccess();
if (item.success) {
item.id = saves[i].getId();
} else {
item.message = saves[i].getErrors()[0].getMessage();
}
results.add(item);
}
res.statusCode = 200;
return results;
}
}The handler follows three rules that keep it bulk-friendly:
- It performs one DML statement for the whole list, not one per record.
- It uses
Database.insertwithallOrNoneset tofalse, so one bad record does not roll back the others. - It returns a result for each input, matched by
index, so the client knows which records failed.
Keep SOQL and DML out of loops
The same rule applies as in triggers. If the handler must look up related data, collect the keys first and query once.
Set<String> names = new Set<String>();
for (AccountInput input : accounts) {
names.add(input.name);
}
Map<String, Account> existing = new Map<String, Account>();
for (Account a : [SELECT Id, Name FROM Account WHERE Name IN :names WITH USER_MODE]) {
existing.put(a.Name, a);
}This uses one query regardless of the batch size. A query inside the for loop would use one query per record and fail at 100 records.
Cap the batch size and the response
An unbounded list is a risk. Pick a maximum (the example uses 200, the size of a trigger chunk) and reject larger requests with a clear status code. Document the limit in your API.
The same applies to @HttpGet. A list endpoint that returns every record will eventually hit the heap or row limit. Add a LIMIT and accept paging parameters such as pageSize and offset or a last-seen Id.
Integer pageSize = 100;
String sizeParam = RestContext.request.params.get('pageSize');
if (sizeParam != null && sizeParam.isNumeric()) {
pageSize = Math.min(Integer.valueOf(sizeParam), 200);
}
List<Account> page = [SELECT Id, Name FROM Account WITH USER_MODE ORDER BY Id LIMIT :pageSize];Flow of a bulk request
Work that is too big for one request
If a job needs more than a synchronous transaction allows, do not push harder. Accept the request, hand the work to asynchronous Apex such as Queueable or Batch Apex, and return quickly. A common pattern is to return 202 Accepted with an identifier the client can use to check progress.
Exercise
A client posts 1,000 accounts to your bulk endpoint, and your handler rejects any request with more than 200 items. Which status code fits best, and what should the client do next?
Show answer
Return 413 (payload too large), with a message that states the 200-item maximum. The client should split its data into chunks of 200 or fewer and send each chunk as a separate request.
Exercise
Why does Database.insert(records, false, AccessLevel.USER_MODE) suit a bulk endpoint better than insert as user records?
Show answer
With allOrNone set to false, valid records are saved and each failure is reported in its own SaveResult. The plain insert as user form throws on the first failure and rolls back the whole batch, so the client cannot tell which records were the problem.