Sub topic 1
The Limits That Make Large Data Hard
Prerequisites
This chapter assumes you can read Apex classes, write SOQL queries, and run basic DML (insert, update, delete). You should also know that Salesforce enforces governor limits. You don't need to have written a batch class yet.
Why Apex has limits
Salesforce runs many customers on shared infrastructure (multitenancy). To keep one customer's code from slowing down everyone else, the platform caps how much work a single transaction can do. A transaction is one unit of Apex work that either commits or rolls back as a whole. The caps are called governor limits, and exceeding one throws an uncatchable System.LimitException that rolls back the transaction.
The limits that matter for large data
These are the main limits for synchronous Apex. Check the current Apex Developer Guide before you rely on exact numbers, because Salesforce can change them.
| Limit | Synchronous value |
|---|---|
| SOQL queries issued | 100 |
| Records returned by SOQL queries | 50,000 |
| DML statements | 150 |
| Records processed by DML | 10,000 |
| Heap size | 6 MB |
| CPU time | 10,000 ms |
| Callouts | 100 |
The 50,000-row query limit is the first wall you hit with large data. A table with five million Accounts cannot be read in one synchronous transaction, however well you write the query. The DML row limit and CPU time follow close behind.
A loop that fails at scale
This code looks reasonable. It works on a small org and fails on a large one.
List<Account> accts = [SELECT Id, Rating FROM Account WHERE Rating = null];
for (Account a : accts) {
a.Rating = 'Cold';
}
update accts;If more than 50,000 Accounts match, the query throws System.LimitException: Too many query rows: 50001. If the query somehow succeeded, the update would still fail once it passed 10,000 records.
Limits are per transaction
Governor limits apply to each transaction, not to your whole data set. Every new transaction starts with fresh counters. If you could split five million records into many small groups and process each group in its own transaction, no single transaction would come near a limit.
Batch Apex does this splitting for you, which later chapters cover in detail.
Common errors
- Querying a whole object into a
Listand hitting the 50,000-row limit. - Running DML or SOQL inside a loop, which burns through the 150 and 100 statement limits.
- Holding large collections in memory and exceeding the heap limit.
- Assuming a
try/catchcan handle aLimitException. It cannot.
Exercise
A synchronous Apex method queries all Contacts in an org with 2 million Contacts. Which limit does it hit first, and why does splitting the work into chunks fix it?
Show answer
It hits the 50,000 query-row limit. Governor limits apply per transaction, so processing the records in chunks, each in its own transaction, gives every chunk a fresh set of limits.