What are the performance and memory trade-offs between stateless and stateful Batch Apex implementations?
Answer
Basics: By default, every execute() starts with the instance variables as they were set at construction; changes made in one chunk are lost. Implementing Database.Stateful makes changes persist, which is handy for totals, error lists and IDs collected for finish().
How it works:
- With Stateful, the batch instance is serialized at the end of each chunk and deserialized at the start of the next.
- Without it, the original state is restored each time.
- Static variables are never preserved, with or without Stateful.
Advanced / deep dive: Stateful costs grow with state size: more serialization CPU per chunk, more heap, and potentially the error "Batchable instance is too big" if the state becomes huge. Unbounded lists (all processed Ids, all errors) are the common culprit across millions of records. Alternatives: write results incrementally to a custom object, accumulate counters rather than collections, use aggregate queries in finish(), or keep reference data in Platform Cache or Custom Metadata. Stateless jobs also avoid subtle bugs from hidden shared state. Combine small Stateful counters with persisted logs for the best of both.
Code / config example:
public class TotalsBatch implements Database.Batchable<SObject>, Database.Stateful {
private Decimal runningTotal = 0; // small accumulator: fine
private Integer failures = 0; // counter, not a list of ids
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Amount FROM Opportunity WHERE IsClosed = true');
}
{
(Opportunity o : scope) { runningTotal += (o.Amount == ? : o.Amount); }
}
{
System.debug( + runningTotal);
}
}