We have an org that has hit:

System.AsyncException: You've exceeded the limit of 100 jobs in the flex queue

and are considering how to avoid that. (As this queue is a shared resource just waiting for the exception and then backing off seems anti-social to other apps that are using the queue; thinking of some kind of randomised back off when the queue is say half full. But is that over complicated?)

I see methods to move items in the queue but no convenient way to check how full the queue is.

Is it necessary to do a count query the AsyncApexJob object and if so are any specific where terms needed? Or is there a method somewhere that returns the size of the queue without consuming the SOQL governor limit?

1 Answer 1


Without waiting for the exception to be thrown, you have to burn a query. I believe the following query should suffice:

Integer flexQueueSize = [SELECT COUNT() FROM AsyncApexJob WHERE Status = 'Holding' FOR UPDATE];

Using FOR UPDATE ensures that you have the correct value of the queue, pending any other requests in flight.

  • What ends up getting locked though?
    – Adrian Larson
    Aug 12, 2016 at 18:07
  • Thanks - exactly what I'm looking for. Have you use the for update part before - no negative effects?
    – Keith C
    Aug 12, 2016 at 18:08
  • @AdrianLarson It holds a lock on all items currently in Holding, and waits to acquire a lock for all jobs that are moving to holding but haven't committed yet. In most practical cases, this is a very small fraction of a second in wait time.
    – sfdcfox
    Aug 12, 2016 at 18:23
  • @KeithC There may be a very small delay in async processing when using FOR UPDATE, but in most cases, this usually won't have an effect. I'd consider using it though if the code that's generating your batches is called fairly frequently.
    – sfdcfox
    Aug 12, 2016 at 18:27
  • Unfortunately you can not use FOR UPDATE along with COUNT in the same query - strange SF restrictions. So I've rewritten it as [SELECT Id FROM ...FOR UPDATE].size().
    – wesaw
    May 17, 2017 at 15:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .