Sub topic 1
The limits that make large data hard
Prerequisites
This chapter assumes you can read and write basic Apex classes, run SOQL queries, and perform DML (insert, update, delete) in Apex. You should also know that Salesforce enforces governor limits. You don't need any batch experience. This chapter explains why batch exists, and later chapters show how to build it.
Why one transaction cannot handle millions of rows
Salesforce runs your code on shared infrastructure. Many customers (tenants) use the same servers and databases. To keep one tenant's code from slowing down the others, the platform caps how much any single piece of Apex can do. These caps are called governor limits.
The limits apply per transaction. A transaction is one unit of work that either commits as a whole or rolls back as a whole. A trigger run, an anonymous Apex execution, or a web service call each runs as its own transaction. When your code exceeds a limit, the platform throws a System.LimitException. You cannot catch this exception, so the whole transaction is rolled back.
If you need to update five million records, a single transaction cannot do it. No version of the code, however efficient, fits five million rows inside the limits below.
The limits that matter most
These are the synchronous per-transaction limits that you hit first when working with large data. Check the current Salesforce documentation for exact values, because limits change between releases.
| Limit | Synchronous value | What it constrains |
|---|---|---|
| SOQL queries issued | 100 | Number of query statements, not rows |
| Records returned by SOQL | 50,000 | Total rows across all queries |
| DML statements | 150 | Number of insert, update, delete calls |
| Records processed by DML | 10,000 | Total rows across all DML statements |
| Heap size | 6 MB | Memory used by variables and collections |
| CPU time | 10,000 ms | Time spent running Apex, not waiting on the database |
| Callouts | 100 | HTTP requests to external systems |
Two points are easy to miss:
- Some limits count statements and others count rows. Moving DML out of a loop helps with the 150-statement limit. It does nothing for the 10,000-row limit.
- The limits apply to the whole transaction, including triggers, flows, and other automation that your code fires. A DML call on Account can run triggers that use up the same query and CPU budget.
Seeing the limits in code
The Limits class reports how much of each limit you have used and what the maximum is. This is the quickest way to learn your headroom while debugging.
System.debug('Queries: ' + Limits.getQueries() + ' / ' + Limits.getLimitQueries());
System.debug('Query rows: ' + Limits.getQueryRows() + ' / ' + Limits.getLimitQueryRows());
System.debug('DML statements: ' + Limits.getDmlStatements() + ' / ' + Limits.getLimitDmlStatements());
System.debug('DML rows: ' + Limits.getDmlRows() + ' / ' + Limits.getLimitDmlRows());
System.debug('Heap: ' + Limits.getHeapSize() + ' / ' + Limits.getLimitHeapSize());
System.debug('CPU ms: ' + Limits.getCpuTime() + ' / ' + Limits.getLimitCpuTime());Run this in anonymous Apex and read the debug log. You can see the maximums immediately. Call the same methods before and after a block of code to measure what that block consumes.
A failing example
The following code looks reasonable. It tries to rate every account that has no rating.
List<Account> accts = [SELECT Id, Rating FROM Account WHERE Rating = null];
for (Account a : accts) {
a.Rating = 'Cold';
}
update accts;In an org with 200 matching accounts, this works. In an org with 2 million, it fails at the query. The query returns more than 50,000 rows, so Salesforce throws System.LimitException: Too many query rows: 50001. Nothing is saved.
Suppose the query succeeded. The update would still fail with Too many DML rows: 10001 once the list grew past 10,000. A list of millions of records would likely also exceed the 6 MB heap limit first.
Three ways the limits fail you
Large data volumes break code in different ways. Knowing which one you face tells you which fix applies.
- Row limits. The query returns too many rows, or DML touches too many. The fix is to process fewer rows per transaction.
- Heap limit. Holding the records in a list uses too much memory. Wide records (many fields, long text) hit this sooner than narrow ones. The fix is to hold fewer records at a time.
- CPU limit. Loops, string handling, and trigger logic add up. Processing 10,000 records with heavy logic can take more than 10 seconds of CPU even though no row limit is reached. The fix is to do less work per transaction.
All three fixes share one idea: do less per transaction, and repeat across many transactions.
Tricks that do not scale
Developers often try to stay within limits using techniques that help a little but do not solve the problem.
- SOQL for loops.
for (Account a : [SELECT Id FROM Account])fetches records in chunks of 200 internally, which relieves heap pressure. However, the 50,000-row query limit still applies to the transaction as a whole. LIMITandOFFSETpagination.OFFSETis capped at 2,000 rows, and repeating queries uses up the 100-query limit.- Bulkification. Moving queries and DML outside loops is essential, and you should always do it. It reduces statement counts but cannot lift the row limits.
- Optimizing CPU. Efficient code buys time, but the row limits stay fixed.
The idea behind the solution
The platform offers asynchronous Apex for work that does not need an immediate answer. Asynchronous transactions run later, in the background, and some of their limits are higher. For example, heap is 12 MB and CPU is 60,000 ms for asynchronous code. These increases are useful but do not change the picture for millions of rows.
Batch Apex addresses the problem directly. It divides the records into chunks, often 200 at a time. It then runs each chunk as its own separate transaction. Every transaction starts with a fresh set of governor limits. The query-row and DML-row limits then apply to each chunk rather than to the whole job.
Compare the two approaches for 2 million records at 200 per chunk:
| Row | One synchronous transaction | Batch Apex |
|---|---|---|
| Transactions | 1 | 10,000 |
| Rows per transaction | 2,000,000 | 200 |
| Limits reset | No | Yes, for every chunk |
| Result | Fails at 50,000 query rows | Completes, one chunk at a time |
One batch-specific detail is worth knowing now. The initial query in a batch job can retrieve up to 50 million records, a far higher ceiling than the 50,000-row synchronous limit. Later chapters explain how this works.
How the limits shape the design
The diagram shows the difference in flow. In a single transaction, all records meet one set of limits. In a batch job, each chunk gets its own.
This is the reason the rest of this tutorial exists. Every feature of Batch Apex, from batch size to state handling to error recovery, follows from the fact that the job is many small transactions rather than one large one.
What you give up
Splitting work into chunks brings trade-offs that you will meet in later chapters.
- No single rollback. Each chunk commits on its own. If chunk 50 fails, chunks 1 to 49 stay saved. You cannot undo the whole job with one rollback.
- No instant result. Batch jobs run asynchronously and wait in a queue. The user does not get an answer in the same request.
- Variables do not persist by default. Each chunk runs in a fresh instance of your class, so a counter you increment in one chunk starts over in the next, unless you take extra steps.
- Ordering is not guaranteed. Do not assume that a record in one chunk is processed before a record in another when your logic depends on it.
Summary
- Governor limits apply per transaction and cap queries, rows, DML, heap, CPU, and callouts.
- A
LimitExceptioncannot be caught and rolls back the whole transaction. - Bulkification and query tuning are necessary but cannot make one transaction process millions of rows.
- Batch Apex runs each chunk as a separate transaction, so limits reset for every chunk.
- The trade-off is that you lose a single rollback, immediate results, and persistent variables.
Exercise
A developer runs update [SELECT Id FROM Contact WHERE Email = null]; in synchronous Apex against an org with 80,000 matching contacts. Which limit does the code hit first, and why does moving the update into a loop of smaller update calls not fix it?
Show answer
The query hits the 50,000 total query rows limit first, so it throws "Too many query rows: 50001" before any update runs. Splitting the update into smaller calls would only change the number of DML statements. The row limits (50,000 query rows, 10,000 DML rows) apply to the whole transaction, so the total number of rows still exceeds them. Only splitting the work across separate transactions, as Batch Apex does, resets the limits.
Exercise
Name two reasons a single transaction can fail on a large data set even if the number of query rows stays under 50,000.
Show answer
The heap limit can be exceeded if the records held in memory are large (many fields or long text), and the CPU time limit can be exceeded if the per-record logic or triggers are expensive. The DML row limit of 10,000 can also be hit, because it is separate from the query row limit.