# What is the purpose of the Database.Stateful interface in Batch Apex, and when must it be implemented?

**Topic:** Apex · **Difficulty:** Medium · **Tags:** Apex, Asynchronous Apex, Batch Apex

Read it on the site: https://www.forcechallenges.com/interview-questions/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:**
```apex
public class OppAmountBatch implements Database.Batchable<SObject>, Database.Stateful {
    private Decimal runningTotal = 0;                 // retained across chunks
    private Integer failed = 0;
    private List<String> errors = new List<String>(); // keep small

    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator('SELECT Id, Amount FROM Opportunity WHERE IsClosed = false');
    }
    public void execute(Database.BatchableContext bc, List<Opportunity> scope) {
        for (Opportunity o : scope) runningTotal += (o.Amount == null ? 0 : o.Amount);
        List<Database.SaveResult> res = Database.update(scope, false);
        for (Database.SaveResult r : res) {
            if (!r.isSuccess()) { failed++; if (errors.size() < 50) errors.add(r.getErrors()[0].getMessage()); }
        }
    }
    public void finish(Database.BatchableContext bc) {
        System.debug('Total=' + runningTotal + ' failed=' + failed);
    }
}
```

**Hidden gotchas & must-remember points:**
- Without Stateful, member changes in `execute` vanish; constructor-set values still persist.
- Static variables never survive between chunks, Stateful or not.
- Large Stateful collections cause slow batches or heap errors; cap or offload them.
- The interface name is exactly `Database.Stateful`.
- Non-serialisable member types break the job.
- Stateful is not needed just to share read-only parameters.

**Best practice:** Keep Stateful state tiny and summary-level, and persist anything important to a log object.

---
Source: ForceChallenges · last updated 2026-11-02
