ApexAdvancedbatchperformanceldv
Tune batch Apex scope size when processing 5 million Opportunity records nightly
Real World Scenario
Territory realignment batch on 5M Opportunities times out in execute method with scope 200 due to heavy per-record SOQL and CPU-intensive territory logic.
Expected Answer
• Reduce scope to 50-100 when CPU-bound; increase when query-row-bound with simple DML
• Pre-query all territory rules and user assignments into maps in start() not execute()
• Order queryLocator by indexed Territory_Id__c for efficient chunking
• Stateful counters only for metrics—not full record lists in instance vars
• Parallel batch jobs partitioned by region Id if no row-lock contention
• Monitor execute duration via custom logging; target under 60s per chunk
• Finish method chains dependent batch only after AsyncApexJob status Completed
Follow-Up Questions & Answers
Click to expand — each follow-up includes a direct, interview-ready answer
Main difference: use case and scale. Reduce scope to 50-100 when CPU-bound; increase when query-row-bound with simple DML. Pre-query all territory rules and user assignments into maps in start() not execute(). Pick based on your integration pattern and team capability. Batch scope is empirical—profile execute() at production data volume, not default 200. Optimize for scale and operational observability.
Architect Perspective
Batch scope is empirical—profile execute() at production data volume, not default 200.