What is the purpose of the Database.Stateful interface in Batch Apex, and when must it be implemented?
Answer
Basics: Batch Apex processes records in chunks (default scope 200, range 1 to 2000), and every chunk is its own transaction. By default the class instance is rebuilt for each transaction, so changes made to member variables in one execute are lost. Implement Database.Stateful alongside Database.Batchable<SObject> when you want those changes preserved.
How it works: After each execute, the platform serialises the instance's non-transient member variables; before the next execute (and finish) it deserialises them. Chunks of one batch job run one after another, so state is safely sequential. Values set in the constructor are available to every execute even without Stateful, because the instance is serialised after construction; what Stateful adds is retaining modifications made during execution.
Advanced / deep dive: The cost is performance and heap: state is serialised and deserialised per chunk, so large collections slow every transaction and can hit the 12 MB async heap limit. Static variables are never preserved. Use transient for members you do not want serialised. Use Stateful for small summaries (record counts, running totals, a capped list of failures, a Set of processed parent Ids). For bigger or more durable output, write to a custom log object or publish platform events instead of carrying it in memory. Stateful does not make chunks run in parallel or share state across different jobs. If the job fails partway, the state may not be reliably reflected in finish, so do not rely on it for critical accounting. Alternatives: aggregate with SOQL AggregateResult in finish, or store checkpoints in a custom object so the job is restartable.
Code / config example: