# What are the performance and memory trade-offs between stateless and stateful Batch Apex implementations?

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

Read it on the site: https://www.forcechallenges.com/interview-questions/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:**
1. With Stateful, the batch instance is serialized at the end of each chunk and deserialized at the start of the next.
2. Without it, the original state is restored each time.
3. 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:**
```apex
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');
    }
    public void execute(Database.BatchableContext bc, List<Opportunity> scope) {
        for (Opportunity o : scope) { runningTotal += (o.Amount == null ? 0 : o.Amount); }
    }
    public void finish(Database.BatchableContext bc) {
        System.debug('Total: ' + runningTotal);
    }
}
```

**Hidden gotchas & must-remember points:**
- Without Stateful, mutated instance variables silently reset each chunk.
- Static variables always reset.
- Large collections in Stateful bloat heap and can cause "Batchable instance is too big".
- Stateful does not guarantee chunk order.
- `transient` fields are not retained.
- Counters are cheap; Id lists are expensive.

**Best practice:** Prefer stateless design and persist results externally; use Stateful only for small counters.

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