I have a scenario where I need to call an API from a trigger that will update a few fields from the API. The trigger is an after insert and is setup to avoid recursion with other triggers on the same object.

Currently I am having the problem of the API (I do not control it) not being able to handle request in parallel. My current code takes an after insert trigger, fires the first apex class with Queueable Interface which checks for if my Oauth token is expired, if it is - request a new one from the API, if not proceed to fire the second Queueable class which makes the request in a loop to get the fields for each of the Salesforce records. This is actually working until we start using alot of records which is necessary. Even at 1000 records split up in batches of 50 via Dataloader it seems like those are too many requests for the API.

So to avoid the problem of having multiple Queueable calls that run in parallel, I was wondering if I should just chain the 2nd Queueable class to itself. Would that hit the Queueable limit of depth. Or is this just something that needs to be moved out of the trigger entirely?

  • 1
    a queueable that chains to another job of the same class is no different than a queueable that chains to a job of a different class
    – cropredy
    Apr 30 '21 at 20:34
  • @cropredy I didn't think of it like that. So it still wont work because each trigger execution will queue more records to hit the API endpoint
    – MMeadows
    Apr 30 '21 at 21:46
  • So your problem is that you have multiple users executing a trigger (hence, possibly in parallel) and each trigger kicks off queueable that ultimately invoke the remote API and the remote API can't handle parallel requests?
    – cropredy
    Apr 30 '21 at 22:02
  • @cropredy no we have one user dataload in several thousand of the records at a time. But the queueable classes are still executing in parallel, which is the problem
    – MMeadows
    May 3 '21 at 14:09
  • 1
    To single thread the queueables: take a look at the dan appleman advanced apex book 4th edition - chapter entitled "Going Asynchronous ". You basically need to store the callout requests in a custom object that a monitor transaction reads from. The book has sample code to do this.
    – cropredy
    May 3 '21 at 15:48

Your Answer

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

Browse other questions tagged or ask your own question.