What are the best practices for handling parent-child relationships across Batch Apex chunks?
Answer
Basics: A batch chunk knows nothing about other chunks. If a parent's children are split across chunks, or a parent is processed in one transaction and its children in another, you can get partial results, duplicate work, or lock errors. The design question is which object drives the batch.
How it works: Pattern 1 (parent-driven): start returns a QueryLocator over parents; execute collects parent Ids, runs one query for children (WHERE ParentId IN :parentIds), processes them, and does one DML. Pattern 2 (child-driven): query children ordered by ParentId, then group by parent in execute. Pattern 3 (create parent and child): insert parents, then read their new Ids and insert children in the same execute, or relate children using an external Id reference without needing a parent Id.
Advanced / deep dive: Locking: updating child records locks the parent in master-detail and rolls up summary relationships, so concurrent batches or user edits on the same parent raise UNABLE_TO_LOCK_ROW. Mitigate by ordering the query by parent, using smaller scopes, avoiding parallel batch jobs touching the same parents, and retrying. Data skew (one parent with more than 10,000 children) makes both locking and chunk boundaries unpredictable; process such parents separately with scope 1 or a dedicated job. If you need whole-parent calculations, do not rely on children in a subquery inside start because subquery rows are not guaranteed to stay together across chunks; re-query children in execute. Cross-chunk accumulation (for example per-parent totals) needs Stateful with a bounded Map, or write intermediate results to a staging object. Always bulkify: one child query and one DML per chunk. For huge volumes consider whether a roll-up summary, Flow or CDC-based design avoids the batch entirely.