+ Start a Discussion
learn_cloudsflearn_cloudsf 

What are the disadvantages of implementing Database.stateful in salesforce ?

What are the disadvantages of implementing Database.stateful in salesforce ?
NagendraNagendra (Salesforce Developers) 
Hi,

Database.stateful implementation fills a list of records and if that list is filled with more than 10000 records at a time and we make that list global then it will result into an error if we query on that list.

Obviously Growing data in your stateful collections may lead to hit heap limits. A batch class as a whole can process 50 million records, 10,000 records per batch and only 10,000 batches per 24 hrs with a state heap limit of 6 MB.

BUT don't even try to go any close to these limits as they may slow it down to a slowest mode.

Some opinions:
  • Don't carry more than 10,000 records in each collection (list or map) during transition between states for "Heap size limits". Often use "Clear" to clear out data after being used.
  • You can also use finish method to call another batch for "CPU time limits"
  • You can use relation build data. for ex: Fetch one record from queryLocator and then fetch other related data on the basis of that record in the execute method. As each batch behaves as a separate program with heap being used as database for them.
  • Keep track of heap with every ending execute and maintain accordingly using this code: Integer startingHeap = Limits.getHeapSize(); Integer addedHeap = Limits.getHeapSize() - startingHeap; and keep removing from collection or saving it temporarily to some temporary Object when you are near to hit limits.
Hope this helps.

Kindly mark this as solved if the reply was helpful.

Thanks,
Nagendra