# Explain the structure of the Database.Batchable interface and how governor limits are handled across batch chunks.

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

Read it on the site: https://www.forcechallenges.com/interview-questions/explain-the-structure-of-the-database-batchable-interface-and-how-governor-limits-are-handled-across-batch

## Answer

**Basics:** Batch Apex handles data volumes too big for one transaction, such as millions of records for cleanups or recalculations.

**How it works:** `start(BatchableContext)` returns a Database.QueryLocator (up to 50 million rows) or an Iterable. `execute(BatchableContext, List<SObject>)` is called for each chunk (scope 1 to 2000, default 200). `finish(BatchableContext)` runs post-processing such as email or chaining another job. Launch with Database.executeBatch(job, scopeSize). Each execute gets its own limits (for example 200 SOQL queries, 60,000 ms CPU, 12 MB heap); limits are not cumulative across chunks.

**Advanced / deep dive:** Instance variables are not preserved between chunks unless the class implements Database.Stateful, which serialises state after each execute; this costs performance and heap. Callouts require Database.AllowsCallouts. Up to 5 batch jobs run concurrently; others wait in Flex Queue (up to 100 Holding jobs), reorderable via the Apex Flex Queue UI or System.FlexQueue. Use Database.update(list, false) for partial success and inspect SaveResult. Iterable-based start is limited by normal query limits (50,000 rows). Monitor via AsyncApexJob and Apex Jobs. If a chunk fails, only that chunk rolls back; other chunks continue.

**Code / config example:**
```apex
public class ContactCleanup implements Database.Batchable<SObject>, Database.Stateful {
    private Integer failures = 0;
    public Database.QueryLocator start(Database.BatchableContext bc) {
        return Database.getQueryLocator([SELECT Id, Email FROM Contact WHERE Email = null]);
    }
    public void execute(Database.BatchableContext bc, List<Contact> scope) {
        for (Contact c : scope) { c.Description = 'No email'; }
        for (Database.SaveResult r : Database.update(scope, false)) {
            if (!r.isSuccess()) failures++;
        }
    }
    public void finish(Database.BatchableContext bc) {
        System.debug('Failures: ' + failures);
    }
}
```

**Hidden gotchas & must-remember points:**
- Static variables reset per chunk; use Database.Stateful for instance state.
- In tests, only one execute scope runs.
- Class edits are blocked while jobs are pending.
- Only call executeBatch from finish for chaining.
- Database.RaisesErrors does not exist; use SaveResult.

**Best practice:** Keep scope size tuned to the work (smaller with callouts) and keep execute idempotent.

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