Sunday, September 17, 2023

Salesforce batch apex best practices

  1. Only use Batch Apex if you have more than one batch of records. If you don't have enough records to run more than one batch, you are probably better off using Queueable Apex.
  2. Use extreme care if you are planning to invoke a batch job from a trigger. You must be able to guarantee that the trigger won’t add more batch jobs than the limit.
  3. Methods declared as future aren’t allowed in classes that implement the Database.Batchable interface.
  4. Methods declared as future can’t be called from a batch Apex class.
  5. All implemented Database.Batchable interface methods must be defined as public or global.
  6. Batch jobs queued before a Salesforce service maintenance downtime remain in the queue. After service downtime ends and when system resources become available, the queued batch jobs are executed. If a batch job was running when downtime occurred, the batch execution is rolled back and restarted after the service comes back up.
  7. To implement record locking as part of the batch job, you can re-query records inside the execute() method, using FOR UPDATE, if necessary. This ensures that no conflicting updates are overwritten by DML in the batch job. To re-query records, simply select the Id field in the batch job's main query locator.
  8. Tune any SOQL query to gather the records to execute as quickly as possible.
  9. Batch Apex jobs run faster when the start method returns a QueryLocator object that doesn't include related records via a subquery. Avoiding relationship subqueries in a QueryLocator allows batch jobs to run using a faster, chunked implementation. If the start method returns an iterable or a QueryLocator object with a relationship subquery, the batch job uses a slower, non-chunking, implementation. For example, if the following query is used in the QueryLocator, the batch job uses a slower implementation because of the relationship subquery: SELECT Id, (SELECT id FROM Contacts) FROM Account                                         
  10. A better strategy is to perform the subquery separately, from within the execute method, which allows the batch job to run using the faster, chunking implementation.

No comments:

Post a Comment