Sub topic 14
Concurrency limits and the Flex Queue
This chapter assumes you can write a batch class, start it with Database.executeBatch, and read the AsyncApexJob record for a job. Here you will learn how many batch jobs an org runs at once, where the extra jobs wait, and how to control that waiting list.
The limit: five active batch jobs
An org can have at most five batch jobs queued or active at the same time. A job counts toward this limit while its status is Queued, Preparing, or Processing. Salesforce may run fewer than five at once when the platform is busy, so treat five as a ceiling.
Before the Flex Queue existed, a sixth Database.executeBatch call failed with an exception. Now the platform accepts the job and parks it. Parked jobs have the status Holding, and they do not count toward the five.
How the Flex Queue works
The Apex Flex Queue is an ordered waiting list for batch jobs that cannot start yet.
- It holds up to 100 jobs in
Holdingstatus. - Jobs are ordered by position. A new job goes to the end by default.
- When one of the five slots frees up, the job at the front moves to
Queuedand then runs normally. - If the Flex Queue already has 100 jobs, a new
Database.executeBatchcall throws an exception, and no job is created.
The statuses you will see on AsyncApexJob are summarized below.
| Status | Meaning | Counts toward the 5-job limit |
|---|---|---|
| Holding | Waiting in the Flex Queue | No |
| Queued | Has a slot and waits for a worker | Yes |
| Preparing | `start` is running | Yes |
| Processing | `execute` calls are running | Yes |
| Completed, Failed, Aborted | Finished | No |
Inspecting the queues
You can count each group with SOQL. Filter on JobType = 'BatchApex' so that Queueable and future jobs are not included.
Integer active = [
SELECT COUNT() FROM AsyncApexJob
WHERE JobType = 'BatchApex'
AND Status IN ('Queued', 'Preparing', 'Processing')
];
Integer holding = [
SELECT COUNT() FROM AsyncApexJob
WHERE JobType = 'BatchApex' AND Status = 'Holding'
];
System.debug('Active: ' + active + ', in Flex Queue: ' + holding);The same view is available in Setup under Apex Flex Queue. You can also reorder jobs there by dragging them.
Reordering and removing held jobs
Only Holding jobs can be reordered. Once a job is Queued, its place is fixed. The System.FlexQueue class changes positions from code.
List<AsyncApexJob> held = [
SELECT Id, ApexClass.Name, CreatedDate
FROM AsyncApexJob
WHERE JobType = 'BatchApex' AND Status = 'Holding'
ORDER BY CreatedDate
];
if (held.size() > 1) {
Id urgent = held[held.size() - 1].Id;
// Make the most recently submitted job the next one to run
Boolean moved = System.FlexQueue.moveJobToFront(urgent);
System.debug('Moved to front: ' + moved);
}The class has these methods:
moveJobToFront(jobId)andmoveJobToEnd(jobId)put a job at either end of the list.moveBeforeJob(jobId, anotherJobId)andmoveAfterJob(jobId, anotherJobId)place a job relative to another held job.- Each method returns
trueif the job moved. It returnsfalse, or throws, if the job is not inHoldingstatus.
To remove a job from the Flex Queue, call System.abortJob(jobId). An aborted job ends with status Aborted and never runs.
Submitting jobs safely
A single executeBatch call is cheap, but a loop that submits many jobs can fill the Flex Queue. Check the room first, then submit.
public class BatchSubmitter {
private static final Integer FLEX_QUEUE_MAX = 100;
// Returns the job Id, or null when the Flex Queue is full
public static Id trySubmit(Database.Batchable<SObject> job, Integer scopeSize) {
Integer holding = [
SELECT COUNT() FROM AsyncApexJob
WHERE JobType = 'BatchApex' AND Status = 'Holding'
];
if (holding >= FLEX_QUEUE_MAX) {
System.debug(LoggingLevel.WARN, 'Flex Queue is full, job not submitted.');
return null;
}
return Database.executeBatch(job, scopeSize);
}
}Call it like this:
Id jobId = BatchSubmitter.trySubmit(new AccountRatingBatch(), 200);There is a small race. Another process can fill the last slot between your count and your submit. Keep the exception path in mind for jobs that must not be lost, and catch the exception if you need to retry.
What the queue does not promise
- Order is not strict. The Flex Queue is first in, first out unless you reorder it. Once jobs are
Queued, the platform decides which one gets the next worker, so do not rely on start order. If job B needs job A's results, chain B from A'sfinishmethod instead of submitting both. - Scheduled jobs use the same queue. A
Schedulableclass that callsDatabase.executeBatchhas no special priority. At 02:00 it can land inHoldingbehind other jobs. The next scheduled run can then start before the previous one has finished, so guard against overlapping runs. - The 5-job limit is per org. A busy sandbox or an unrelated managed package can use the slots your job needs.
- Other async limits still apply. Every
executecall counts toward the org's daily limit on asynchronous Apex executions. Many small batches over millions of records use that allowance quickly.
Guarding against overlap
A nightly job that takes longer than 24 hours, or that waits a long time in Holding, can pile up. Before starting the job, check whether it is already pending or running.
public class NightlyAccountRatingJob implements Schedulable {
public void execute(SchedulableContext sc) {
Integer pending = [
SELECT COUNT() FROM AsyncApexJob
WHERE JobType = 'BatchApex'
AND ApexClass.Name = 'AccountRatingBatch'
AND Status IN ('Holding', 'Queued', 'Preparing', 'Processing')
];
if (pending == 0) {
Database.executeBatch(new AccountRatingBatch(), 200);
} else {
System.debug('Previous run still pending, skipping this one.');
}
}
}Skipping is safe here because the batch selects only accounts with Rating = null. If a run is skipped, the next run picks up the same work. This is the same re-runnable design the later chapter on large volumes recommends.
Common mistakes
- Submitting one batch job per record or per small group from a trigger. This fills the five slots, then the Flex Queue, and then fails.
- Assuming
Database.executeBatchreturning an Id means the job is running. It may beHolding. - Polling
AsyncApexJobin a loop inside Apex to wait for a job. Usefinishor chaining instead. - Trying to reorder a
Queuedjob. OnlyHoldingjobs can move.
Exercise
An org already has five batch jobs in Processing status and 30 in the Flex Queue. You call Database.executeBatch for a new job. What status does it get, and where does it sit in the Flex Queue?
Show answer
It gets the status Holding, because all five slots are used. It is placed at the end, in position 31, unless you move it with System.FlexQueue or the Apex Flex Queue page in Setup.
Exercise
A nightly Schedulable starts a batch that sometimes spends hours in Holding. Two nights in a row, the job from the previous night is still pending when the next one is scheduled. How do you prevent duplicate runs?
Show answer
Before calling Database.executeBatch in the Schedulable, query AsyncApexJob for the batch class with a Status of Holding, Queued, Preparing, or Processing. Start the new job only if the count is zero. The batch should also select only unprocessed records, so a skipped night is made up on the next run.