Explain the structure of the Database.Batchable interface and how governor limits are handled across batch chunks.
Answer
Basics: Batch Apex handles data volumes too big for one transaction, such as millions of records for cleanups or recalculations.
How it works: start(BatchableContext) returns a Database.QueryLocator (up to 50 million rows) or an Iterable. execute(BatchableContext, List<SObject>) is called for each chunk (scope 1 to 2000, default 200). finish(BatchableContext) runs post-processing such as email or chaining another job. Launch with Database.executeBatch(job, scopeSize). Each execute gets its own limits (for example 200 SOQL queries, 60,000 ms CPU, 12 MB heap); limits are not cumulative across chunks.
Advanced / deep dive: Instance variables are not preserved between chunks unless the class implements Database.Stateful, which serialises state after each execute; this costs performance and heap. Callouts require Database.AllowsCallouts. Up to 5 batch jobs run concurrently; others wait in Flex Queue (up to 100 Holding jobs), reorderable via the Apex Flex Queue UI or System.FlexQueue. Use Database.update(list, false) for partial success and inspect SaveResult. Iterable-based start is limited by normal query limits (50,000 rows). Monitor via AsyncApexJob and Apex Jobs. If a chunk fails, only that chunk rolls back; other chunks continue.
Code / config example:
public class ContactCleanup implements Database.Batchable<SObject>, Database.Stateful {
private Integer failures = ;
Database.QueryLocator {
Database.getQueryLocator([SELECT Id, Email FROM Contact ]);
}
{
(Contact c : scope) { c.Description = ; }
(Database.SaveResult r : Database.update(scope, )) {
(!r.isSuccess()) failures++;
}
}
{
System.debug( + failures);
}
}