Sub topic 2
What Batch Apex is and when to use it
This chapter assumes you can write Apex classes, run SOQL queries and DML statements, and know that governor limits cap what one transaction can do. It explains what Batch Apex is and how to decide whether a job needs it. Later chapters cover the interface in detail.
The idea: one big job, many small transactions
Batch Apex splits a large set of records into chunks and processes each chunk in its own transaction. Salesforce resets governor limits at the start of every transaction. A job that would exceed the limits in one synchronous run can therefore finish as many small runs, each within the limits.
A synchronous transaction can query at most 50,000 records and run at most 150 DML statements. Batch Apex gets past these limits in two ways:
- The
startmethod returns aQueryLocator, which can supply up to 50 million records to the job. - Each chunk, called a batch, runs in a separate
executecall with a fresh set of limits.
The default chunk size is 200 records. You can change it when you start the job.
How a job runs
A batch class implements Database.Batchable<SObject>. Salesforce calls its methods in a fixed order.
startruns once and defines the records to process.executeruns once per chunk. Each call is its own transaction.finishruns once after all chunks are done. Use it for summaries, notifications or starting a follow-up job.
Here is a minimal class.
public class AccountRatingBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([
SELECT Id, Rating FROM Account WHERE Rating = null
]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Rating = 'Cold';
}
update scope;
}
public void finish(Database.BatchableContext bc) {
System.debug('Job ' + bc.getJobId() + ' finished.');
}
}If this ran as one synchronous update over a million accounts, it would fail on the row limits. As a batch job, each execute call updates 200 accounts, and the job continues until the query results are used up.
When to use Batch Apex
Batch Apex fits work that is large, can run in the background and does not need an immediate answer. Typical cases are:
- Data cleanup or mass updates across many records.
- Recalculating fields after a business rule changes.
- Archiving or deleting old records.
- Nightly integrations that process large volumes.
It is a poor fit in these cases:
- A user is waiting for the result on screen.
- The work involves a few hundred records or fewer, where a Queueable job is simpler.
- The records must be processed in a strict order. Chunks are not guaranteed to run in the order you expect.
Trade-offs
Each chunk is a separate transaction. If chunk 3 fails, chunks 1 and 2 stay committed. Batch Apex does not roll back the whole job, so you have to design for partial progress. Later chapters cover this.
Batch jobs also run asynchronously. They wait in a queue and start when resources are free, so you cannot rely on a specific start time.
Exercise
A job must update 2 million Contact records overnight. Why does Batch Apex work where a single synchronous update does not?
Show answer
A synchronous transaction is capped at 50,000 queried rows and 150 DML statements. Batch Apex lets start return a QueryLocator over millions of records. It then processes them in chunks, usually 200 at a time. Each chunk runs in its own execute transaction with fresh governor limits.