0

I have a custom Object (Bulk Order) and a child (Bulk Order Line). I have a trigger on Bulk Order object to call a batch apex when Bulk Order record status is = 'In progress'.

My question is: Imagine i have 250 Bulk Order records with 100 lines each. If i perform an update on all the Bulk Order records, does anyone know which will be the Salesforce behavior?

  • Should i expect all of them to run sequentially?
  • Will i have a problem due to the limitation of 5 concurrent APEX jobs?
  • Will i get another problem?

2 Answers 2

2

From what you've said, you will Database.executeBatch for each chunk passed to your Bulk Order trigger. If you have, for example, 250 Bulk Orders created or updated in a single DML then this will call executeBatch twice; once with 200 and the other with 50. These may or may not run concurrently depending on other executing batches and any in the flex queue (plus any number of other multi-tenant architecture reasons). Remember, too, that once you have 100 batches waiting in the flex queue all further requests to Database.executeBatch will simply fail with an exception.

This is a fragile design, very much open to hitting limits.

I recommend detaching the execution of the batch from the trigger via use of Platform Events and a "flag" on the record that indicates it needs processing. You'll find a longer explanation of our "Adaptive Batch" pattern in this previous Q&A.

1
  • Thanks a lot, Phil for the detailed explanation! Oct 6, 2021 at 15:14
2

Salesforce directly warns against using Batchable in a trigger context, or at least exercising caution (one such example is here):

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.

It is almost never the appropriate solution, given the limit of five concurrent batches, only one start method allowed at a time (which can run for up to 10 minutes), and the flex queue size of 100 batches. In a trigger, consider using Future or Queueable methods only.

If you absolutely need to handle large amounts of data from a trigger, just flag the records somehow and use a Schedulable class to periodically perform asynchronous updates. This is far less fragile than calling Batchable directly.

1
  • Thanks a lot, sfdcfox for the detailed explanation! Oct 6, 2021 at 15:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.