Sub topic 8
Sharing state across batches with Database.Stateful
This chapter assumes you can write a basic Database.Batchable class with start, execute and finish, and that you know how to start it with Database.executeBatch. It also assumes you are comfortable with Database.update(records, false) and Database.SaveResult. If the lifecycle of a batch job is new to you, review the anatomy chapter first.
Why batch jobs forget things
A batch job processes records in chunks, and each chunk runs in its own transaction. Salesforce does not keep one object in memory for the whole job. By default, every execute call works on a fresh copy of your class, built from the state the instance had when the job was queued. Anything you change in a member variable during one execute is gone when the next one starts.
Consider this counter:
public class CounterBatch implements Database.Batchable<SObject> {
public Integer processed = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([SELECT Id FROM Account]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
processed += scope.size();
}
public void finish(Database.BatchableContext bc) {
System.debug('Processed: ' + processed);
}
}With 1,000 accounts and a batch size of 200, you would expect finish to print 1000. It prints 0. Each execute started with processed = 0, added 200 and discarded the result. The finish method also runs on a fresh copy.
How Database.Stateful works
Adding the marker interface Database.Stateful changes this behavior. A marker interface has no methods to implement. After each execute call, Salesforce serializes the instance, meaning it converts the member variables to a stored form. Before the next execute call, and before finish, it deserializes that form back into an object.
public class CounterBatch implements Database.Batchable<SObject>, Database.Stateful {
public Integer processed = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([SELECT Id FROM Account]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
processed += scope.size();
}
public void finish(Database.BatchableContext bc) {
System.debug('Processed: ' + processed);
}
}Now finish prints 1000.
What is and is not kept
Stateful applies only to instance member variables. The table summarizes the common cases.
| Data | Kept across execute calls? |
|---|---|
| Instance variable, no Stateful | No. Resets on every call. |
| Instance variable, with Stateful | Yes. |
| Instance variable set in the constructor | Yes, as the starting value. Changes made in `execute` persist only with Stateful. |
| Static variable | No, with or without Stateful. Statics reset for every transaction. |
| `transient` instance variable | No. It is skipped during serialization. |
| `Database.BatchableContext` | Not state. Each call gets its own context. |
The constructor row matters. If you pass configuration into the constructor, such as a record type name or a cutoff date, every execute can read it without Stateful. You need Stateful only when execute must write something that later calls or finish will read.
A practical example: totals and failed Ids
The following job rates accounts and collects results for a summary. It counts successes and failures, and it remembers the Ids of failed records so finish can report them.
public class AccountRatingBatch implements Database.Batchable<SObject>, Database.Stateful {
private static final Integer MAX_TRACKED_FAILURES = 500;
public Integer succeeded = 0;
public Integer failed = 0;
public List<Id> failedIds = new List<Id>();
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';
}
List<Database.SaveResult> results = Database.update(scope, false);
for (Integer i = 0; i < results.size(); i++) {
if (results[i].isSuccess()) {
succeeded++;
} else {
failed++;
if (failedIds.size() < MAX_TRACKED_FAILURES) {
failedIds.add(scope[i].Id);
}
}
}
}
public void finish(Database.BatchableContext bc) {
System.debug('Succeeded: ' + succeeded + ', failed: ' + failed);
System.debug('First failed Ids: ' + failedIds);
}
}Two details deserve attention. The index i links each SaveResult to the record at the same position in scope, because Database.update returns results in input order. The list is also capped at 500 entries. The reason for the cap is covered next.
The costs of keeping state
Stateful is not free. Keep these points in mind.
- Serialization overhead. Every chunk pays to save and restore the instance. A Stateful job with large state runs slower than the same job without it.
- Heap growth. Asynchronous Apex has a 12 MB heap limit, and the whole instance counts against it in every
execute. AList<Id>orMapthat gains entries on each chunk can exceed that limit after thousands of chunks, even though each chunk looked fine on its own. Accumulate totals and small samples, not the data itself. - Serializable members only. Members must be types that Apex can serialize. Many system types and some objects cannot be saved. If a member cannot be serialized, the job fails at runtime, often in a later chunk instead of the first one.
- Failed chunks. An unhandled exception in
executerolls back that chunk's DML. Do not assume your counters include a chunk that threw, and catch exceptions when you need an accurate count.
Choosing between Stateful and other options
Use Stateful when you need totals, a small sample of errors, or a value computed in one chunk and read in the next. Skip it when each chunk is independent and finish needs nothing from the run. In that case you can query the job's built-in numbers instead.
AsyncApexJob already reports JobItemsProcessed, TotalJobItems and NumberOfErrors. Note that these count chunks, not records, and NumberOfErrors counts chunks that failed with unhandled exceptions. They do not tell you how many records failed when you use allOrNone = false. That gap is the usual reason to add your own counters.
Testing a Stateful job
Instance variables are readable after Test.stopTest() only if you keep a reference to the batch object. Create the instance first, pass it to executeBatch, then read its fields.
@IsTest
private class AccountRatingBatchTest {
@TestSetup
static void setup() {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 150; i++) {
accts.add(new Account(Name = 'Test ' + i));
}
insert accts;
}
@IsTest
static void countsSucceededRecords() {
AccountRatingBatch job = new AccountRatingBatch();
Test.startTest();
Database.executeBatch(job, 200);
Test.stopTest();
System.assertEquals(150, [SELECT COUNT() FROM Account WHERE Rating = 'Cold']);
System.assertEquals(150, job.succeeded);
System.assertEquals(0, job.failed);
}
}A test runs only one execute call, so this test cannot prove that state survives between chunks. It confirms that your counting logic is correct. Verify multi-chunk behavior with a small run in a sandbox, using a batch size of 10 against a few hundred records.
Common mistakes
- Forgetting
Database.Statefuland seeing counters of zero infinish. - Using
staticvariables for counters. - Storing full
SObjectlists in a member variable, which grows the heap on each chunk. - Declaring a member as
transientand expecting it to persist. - Assuming
AsyncApexJob.NumberOfErrorsequals the number of failed records.
Exercise
A batch class declares public static Integer total = 0; and implements Database.Stateful. Each execute call adds scope.size() to total. The job processes 1,000 records with a batch size of 200. What does finish see, and how do you fix it?
Show answer
finish sees 0. Static variables are not serialized by Database.Stateful and reset for every transaction, so the additions are lost. Change the field to a non-static instance variable (public Integer total = 0;) and keep Database.Stateful on the class. finish then sees 1000.
Exercise
A Stateful job stores every failed record's Id in a List<Id> across 5 million records, and it fails with a heap error late in the run. Name the cause and two ways to reduce the risk.
Show answer
The list grows with every chunk, and the whole instance counts toward the 12 MB asynchronous heap limit in each execute call. Two fixes: cap the list at a fixed size and keep only a sample, or write failures to a custom log object (or publish a platform event) from execute and keep only counters in memory.