# How does the Iterable interface work in Batch Apex for custom data collections?

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

Read it on the site: https://www.forcechallenges.com/interview-questions/how-does-the-iterable-interface-work-in-batch-apex-for-custom-data-collections

## Answer

**Basics:** When the work list is not a simple SOQL result, such as records parsed from an external API, a merge of two objects, or a filtered subset that SOQL cannot express, you return an `Iterable` from `start()` instead of a QueryLocator.

**How it works:**
1. Implement `Database.Batchable<T>`; `start()` returns `Iterable<T>` (a `List` already qualifies, or write a class implementing `Iterable` and `Iterator`).
2. The framework calls `iterator()`, then `hasNext()` and `next()` to build each scope.
3. Each scope goes to its own `execute()` transaction.
4. Add `Database.AllowsCallouts` if `execute()` makes callouts (`start()` itself can make callouts only with it as well).

**Advanced / deep dive:** `start()` runs as one transaction, so the 50,000 SOQL row limit, heap (6 MB sync context rules apply in start; batch start runs as async with 12 MB) and CPU apply to everything you assemble. A custom `Iterator` can lazily generate items to keep memory low, but the iterator object is serialized between chunks, so keep it small and serializable. For huge but structured data, prefer a QueryLocator; or paginate: have `start()` return only IDs or page tokens and fetch details in `execute()`. Apex Cursors (newer feature, verify availability in your release) are another way to page through large SOQL results in async code.

**Code / config example:**
```apex
public class ExternalIdBatch implements Database.Batchable<SObject>, Database.AllowsCallouts {
    public Iterable<SObject> start(Database.BatchableContext bc) {
        // Build a list that SOQL alone cannot express
        List<SObject> work = new List<SObject>();
        for (Account a : [SELECT Id, Name FROM Account WHERE Name LIKE 'Acme%' LIMIT 20000]) {
            work.add(a);
        }
        return work; // List implements Iterable
    }
    public void execute(Database.BatchableContext bc, List<SObject> scope) {
        // process this chunk
    }
    public void finish(Database.BatchableContext bc) {}
}
```

**Hidden gotchas & must-remember points:**
- The 50 million record advantage does not apply; the 50,000 SOQL row limit does inside `start()`.
- Returning a giant list risks the heap limit before any chunk runs.
- The iterator and the batch instance must be serializable.
- Scope size still applies (1 to 2000, default 200).
- Without `Database.AllowsCallouts`, callouts in `start()` or `execute()` throw an exception.

**Best practice:** Keep the Iterable thin, return identifiers or small objects, and load heavy details inside `execute()`.

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