Salesforce Decode
Salesforcedecode
Back to questions
ApexIntermediatebatchstateful

Use Database.Stateful in batch Apex for running totals

Real World Scenario

Batch must track cumulative error count across execute methods for finish email summary.

Expected Answer

• Implement Database.Stateful on batch class • Persist instance variables across execute invocations • Avoid storing large collections in stateful vars—heap risk • Reset counters carefully in test multiple execute simulation • Finish method reads accumulated state for reporting • Document thread safety—single batch instance

Follow-Up Questions & Answers

Click to expand — each follow-up includes a direct, interview-ready answer

Main difference: use case and scale. Implement Database.Stateful on batch class. Persist instance variables across execute invocations. Pick based on your integration pattern and team capability. Stateful batch is for counters and flags, not full record caches. Balance speed of delivery with maintainability.

Architect Perspective

Stateful batch is for counters and flags, not full record caches.