Sub topic 13
Governor limits and bulk-friendly endpoints
This chapter assumes you can write an @RestResource class with @HttpGet and @HttpPost methods and read the request through RestContext. It also assumes you know SOQL, DML, and the basics of Apex tests. Here you will see how governor limits apply to a REST call and how to design endpoints that stay inside them when a client sends many records at once.
Each request is one transaction
Every call to an Apex REST endpoint runs as a separate synchronous Apex transaction. The platform resets the limit counters at the start of each call. Two consequences follow:
- Your code cannot spend limits "across" calls. If a client makes 500 calls, each call gets a fresh budget.
- Everything that runs inside one call shares one budget. That includes your handler, any triggers, flows, and validation rules fired by your DML, and any helper classes you call.
The second point causes most production failures. A handler that looks cheap can fail once a trigger on Account runs a query for each batch of records.
The limits that matter most for a synchronous REST handler are these:
| Limit | Synchronous value | Typical way to hit it |
|---|---|---|
| SOQL queries | 100 | A query inside a loop over request items |
| Rows returned by SOQL | 50,000 | A GET with no filter or no `LIMIT` |
| DML statements | 150 | An `insert` or `update` inside a loop |
| Rows processed by DML | 10,000 | A very large list in the request body |
| CPU time | 10,000 ms | Nested loops, heavy JSON processing |
| Heap size | 6 MB | Deserializing a large body and building a large response |
| Callouts | 100 per transaction | One callout per item in the body |
Check the current Salesforce documentation for exact values, because they can change between releases. A request or response over the platform's size cap is rejected before your code finishes, so a payload cap is a limit you also have to design for.
Salesforce also limits how many long-running requests an org can have at the same time. Long-running synchronous requests (those that run more than a few seconds) compete for a small pool of slots. One slow endpoint that many clients call at once can block other users' requests, so keep endpoints fast and move heavy work to asynchronous Apex.
What "bulk-friendly" means for a REST endpoint
A bulk-friendly endpoint follows three rules:
- It accepts a collection when callers commonly work with many records. One call with 100 items beats 100 calls with one item each, because it avoids network round trips and repeated authentication overhead.
- It uses a fixed number of SOQL and DML statements no matter how many items arrive. The cost may grow with CPU time and heap, but not with the query or DML statement count.
- It enforces a maximum batch size and tells the client what that size is.
The anti-pattern: queries and DML in loops
This handler works for one item and fails for 101:
@HttpPost
global static void badHandler(List<String> accountIds) {
for (String accId : accountIds) {
Account a = [SELECT Id, Name FROM Account WHERE Id = :accId];
a.Description = 'Checked';
update a;
}
}With 101 Ids, the 101st query throws System.LimitException: Too many SOQL queries: 101. This exception cannot be caught. The transaction ends, all DML rolls back, and the client receives an error response. The 151st update would fail the same way.
The fix is to query once, work in memory, and run one DML statement:
@HttpPost
global static void goodHandler(List<Id> accountIds) {
List<Account> accounts = [
SELECT Id, Description
FROM Account
WHERE Id IN :accountIds
WITH USER_MODE
];
for (Account a : accounts) {
a.Description = 'Checked';
}
update as user accounts;
}The statement count stays at one query and one DML call whether accountIds holds 5 items or 200.
A complete bulk resource
The class below exposes two endpoints on one resource. The GET method reads a comma-separated ids query parameter. The POST method accepts a JSON list of accounts and returns one result per item. Both enforce a batch cap of 200.
@RestResource(urlMapping='/v1/AccountBatch/*')
global with sharing class AccountBatchService {
private static final Integer MAX_BATCH = 200;
global class AccountInput {
global String name;
global String industry;
}
global class ItemResult {
global Integer index;
global Id id;
global Boolean success;
global String message;
}
@HttpGet
global static List<Account> getAccounts() {
RestResponse res = RestContext.response;
String raw = RestContext.request.params.get('ids');
if (String.isBlank(raw)) {
res.statusCode = 400;
return new List<Account>();
}
List<String> parts = raw.split(',');
if (parts.size() > MAX_BATCH) {
res.statusCode = 400;
return new List<Account>();
}
Set<Id> ids = new Set<Id>();
for (String part : parts) {
try {
ids.add((Id) part.trim());
} catch (Exception e) {
res.statusCode = 400;
return new List<Account>();
}
}
return [
SELECT Id, Name, Industry
FROM Account
WHERE Id IN :ids
WITH USER_MODE
LIMIT :MAX_BATCH
];
}
@HttpPost
global static List<ItemResult> createAccounts(List<AccountInput> accounts) {
RestResponse res = RestContext.response;
List<ItemResult> results = new List<ItemResult>();
if (accounts == null || accounts.isEmpty() || accounts.size() > MAX_BATCH) {
res.statusCode = 400;
ItemResult err = new ItemResult();
err.success = false;
err.message = 'Send between 1 and ' + MAX_BATCH + ' accounts per request.';
results.add(err);
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 r = new ItemResult();
r.index = i;
r.success = saves[i].isSuccess();
if (r.success) {
r.id = saves[i].getId();
} else {
r.message = saves[i].getErrors()[0].getMessage();
}
results.add(r);
}
return results;
}
}A few design choices are worth noting.
- One statement per concern. The GET uses one query. The POST uses one DML call. Neither count depends on the batch size.
- Binding a set.
WHERE Id IN :idsbinds a whole collection in one query. Validating each Id with a cast before the query returns a clean 400 instead of an unhandled exception. LIMIT :MAX_BATCH. The query cannot return more rows than the response should carry, even if the cap check above it is later removed.- Partial success.
Database.insert(records, false, ...)lets valid records save while invalid ones report errors. With the defaultinsertstatement, one bad record rolls back the whole batch. Partial success suits batch endpoints because the client gets a result for every item, in the same order it sent them. - Per-item results. The
indexfield lets the client match each result to its input without relying on position alone.
A request body for the POST looks like this. The parameter name accounts must match the top-level JSON key:
{
"accounts": [
{ "name": "Acme Corp", "industry": "Technology" },
{ "name": "Globex", "industry": "Energy" },
{ "industry": "Retail" }
]
}The third item has no name. Because Name is required, that item fails with a required-field message while the first two are created. The response is still HTTP 200, so clients must check each success flag.
Triggers and automation share your budget
When the POST above inserts 200 accounts, any before insert and after insert triggers run once for the whole list of 200 records, in chunks. Flows, process automation, and validation rules also run. They all draw from the same 100 queries, 150 DML statements, and 10-second CPU budget as your handler.
This is why the batch cap should be chosen by measurement, not by what a single DML statement can theoretically handle. In an org with heavy automation on Account, 200 records per request may be too many. Lower the cap to 50 and document it. A cap that leaves a safe margin is better than one that fails on a busy day.
You can inspect the budget from inside the handler with the Limits class:
System.debug('SOQL used: ' + Limits.getQueries() + ' / ' + Limits.getLimitQueries());
System.debug('DML statements used: ' + Limits.getDmlStatements() + ' / ' + Limits.getLimitDmlStatements());
System.debug('DML rows used: ' + Limits.getDmlRows() + ' / ' + Limits.getLimitDmlRows());
System.debug('CPU ms used: ' + Limits.getCpuTime() + ' / ' + Limits.getLimitCpuTime());
System.debug('Heap bytes used: ' + Limits.getHeapSize() + ' / ' + Limits.getLimitHeapSize());Use these in tests and while developing to find out how close a realistic batch comes to a limit. Remove noisy debug statements before you deploy.
Testing the bulk behavior
A bulk endpoint needs a test that sends a full batch. A test with only one record cannot reveal a query inside a loop. The test below sends the maximum batch plus one invalid item, then checks both the results and the statement counts:
@IsTest
private class AccountBatchServiceTest {
@IsTest
static void createsFullBatchWithOneInvalidItem() {
RestContext.request = new RestRequest();
RestContext.response = new RestResponse();
List<AccountBatchService.AccountInput> inputs =
new List<AccountBatchService.AccountInput>();
for (Integer i = 0; i < 199; i++) {
AccountBatchService.AccountInput input = new AccountBatchService.AccountInput();
input.name = 'Bulk Account ' + i;
input.industry = 'Technology';
inputs.add(input);
}
// One item with no name, which must fail on its own.
inputs.add(new AccountBatchService.AccountInput());
Test.startTest();
List<AccountBatchService.ItemResult> results =
AccountBatchService.createAccounts(inputs);
Integer dmlUsed = Limits.getDmlStatements();
Test.stopTest();
Assert.areEqual(200, results.size());
Assert.isFalse(results[199].success);
Assert.areEqual(199, [SELECT COUNT() FROM Account]);
Assert.areEqual(1, dmlUsed);
}
@IsTest
static void rejectsOversizedBatch() {
RestContext.request = new RestRequest();
RestContext.response = new RestResponse();
List<AccountBatchService.AccountInput> inputs =
new List<AccountBatchService.AccountInput>();
for (Integer i = 0; i < 201; i++) {
inputs.add(new AccountBatchService.AccountInput());
}
List<AccountBatchService.ItemResult> results =
AccountBatchService.createAccounts(inputs);
Assert.areEqual(400, RestContext.response.statusCode);
Assert.isFalse(results[0].success);
}
}Test.startTest() gives the code under test a fresh set of limits, so the counts reflect your handler and its triggers and not the test setup. If the org has triggers that run extra DML, the dmlUsed assertion will show it. Adjust the expected number only after you understand why it changed.
Common failures and how to read them
| Symptom | Likely cause | Fix |
|---|---|---|
| `Too many SOQL queries: 101` | A query in a loop, or a trigger that queries per record | Move queries out of loops and bind collections |
| `Too many DML statements: 151` | DML in a loop | Collect records in a list and run one statement |
| `Apex CPU time limit exceeded` | Nested loops, or automation on a large batch | Use maps for lookups, lower the batch cap, move work to Queueable Apex |
| `Apex heap size too large` | Building a large response list in memory | Return fewer fields and fewer rows, and add paging |
| `REQUEST_LIMIT_EXCEEDED` for concurrency | Many long-running requests at once | Make the endpoint faster, or return quickly and queue the work |
When a limit is the real constraint, move the heavy work off the request path. The endpoint validates the input, enqueues a Queueable job, and returns HTTP 202 with an identifier. The client can then fetch status from a second GET endpoint. This keeps the synchronous call short and lets the asynchronous job use higher limits.
Summary of rules
- Treat every REST call as one transaction that shares its limits with triggers and flows.
- Never put SOQL or DML inside a loop over request items.
- Bind collections with
IN :collectionand use maps for in-memory lookups. - Cap the batch size, return a 400 when it is exceeded, and choose the cap by testing against your org's automation.
- Use partial-success DML and return one result per item for batch writes.
- Test with a full batch, not a single record.
Exercise
A client posts 150 account Ids to your endpoint, and the handler throws "Too many SOQL queries: 101". The handler contains a for loop over the Ids. Describe the fix, and name one thing outside your own code that could still push the transaction over the limit after the fix.
Show answer
Replace the per-Id query with one query that uses WHERE Id IN :ids (a Set or List bound once), then work with the results in memory, for example in a Map<Id, Account>. After the fix the handler uses one query regardless of batch size. Triggers, flows, or other automation on the objects you modify run in the same transaction and share the same 100-query budget, so they can still exceed it. Test with a full-size batch in an org with the real automation, and lower the batch cap if needed.
Exercise
Why does the createAccounts method call Database.insert(toInsert, false, AccessLevel.USER_MODE) instead of insert as user toInsert, and what must a client check in the response?
Show answer
The false argument allows partial success. Valid records are saved and invalid ones return errors, so the handler can report a result for every item. A plain insert as user statement is all-or-none, so one bad record would roll back the whole batch with a single exception. Because the endpoint returns HTTP 200 even when some items fail, the client must check the success flag and message of each item in the results list and not rely on the status code alone.
Exercise
Your endpoint must process 5,000 records by calling external logic that takes about 30 seconds in total. Why is a single synchronous POST a poor design, and what is a better one?
Show answer
A synchronous call that runs for a long time risks CPU, heap, and callout-time limits, and it occupies one of the org's limited slots for long-running requests, which can block other users. A better design validates the input, enqueues a Queueable (or Batch) Apex job, and returns HTTP 202 with a job identifier right away. The client then polls a second GET endpoint for the job status and results, and the asynchronous job runs with higher limits.