# What factors determine the optimal batch size parameter when calling Database.executeBatch()?

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

Read it on the site: https://www.forcechallenges.com/interview-questions/what-factors-determine-the-optimal-batch-size-parameter-when-calling-database-executebatch

## Answer

**Basics:** `Database.executeBatch(job, size)` sets how many records are handed to each `execute()`. Each chunk is its own transaction, so size trades fewer transactions (faster, fewer async executions) against the risk of hitting a limit and failing the whole chunk.

**How it works:**
1. Records are sliced into scopes of the given size.
2. Each scope runs in its own transaction with fresh limits (async: 12 MB heap, 60,000 ms CPU, 200 SOQL).
3. If any uncaught error or limit hit occurs, only that chunk rolls back.

**Advanced / deep dive:** Reduce the size when: there is one callout per record (max 100 callouts per transaction, so size at most 100 or fewer), triggers, flows or heavy logic run on the DML, records carry large text or blob fields, or parent-record row locks (UNABLE_TO_LOCK_ROW) appear when many children update the same parent. Increase it for light-touch updates to cut the count of executions, which count toward the daily async limit (greater of 250,000 or licenses x 200). Measure with `Limits.getCpuTime()` and `Limits.getHeapSize()` logged in `execute()`, and look at Apex Jobs for time per batch. Making the size configurable (Custom Metadata) lets admins tune without a deployment. Also remember `Database.Stateful` growth and that chunk order is not guaranteed.

**Code / config example:**
```apex
// Conservative size for a job that does one callout per record
Id jobId = Database.executeBatch(new SyncBatch(), 50);

// Size from Custom Metadata so it can be tuned without deploying
Batch_Config__mdt cfg = Batch_Config__mdt.getInstance('SyncBatch');
Integer size = (cfg != null && cfg.Scope_Size__c != null) ? Integer.valueOf(cfg.Scope_Size__c) : 200;
Database.executeBatch(new SyncBatch(), size);
```

**Hidden gotchas & must-remember points:**
- Valid range is 1 to 2000; default 200.
- A chunk that exceeds any limit fails entirely; other chunks continue.
- With callouts, size must stay at or below the callout limit per transaction (100) per call you make per record.
- Larger scope means more records rolled back on a failure.
- Lock contention is fixed by smaller scope or by ordering the query by the parent Id.
- Scheduled-job UI scheduling uses the default 200.

**Best practice:** Start at 200, test with production-like volume, and set size by the tightest limit your execute logic touches.

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