What is the Flex Queue in Salesforce Asynchronous Apex, and how does it manage waiting batch jobs?
Answer
Basics: Batch Apex lets you process large data sets in chunks. Without the Flex Queue, submitting a sixth concurrent batch would fail. Now Database.executeBatch() accepts the job, parks it as Holding, and starts it automatically when a slot opens. It solves the "too many concurrent batches" problem for bursty workloads such as many integrations or schedules firing together.
How it works:
Database.executeBatch(job, size)is called.- If fewer than 5 batch jobs are queued/active (statuses Queued, Preparing, Processing), the job gets a normal slot.
- Otherwise it goes to the Flex Queue with status
Holding, ordered first-in, first-out. - When a slot frees, the job at the front moves to
Queued, thenPreparingandProcessing. - Admins can reorder Holding jobs in Setup, Apex Flex Queue, or via Apex.
Advanced / deep dive: Only batch jobs (including those started by System.scheduleBatch or by a scheduled class) use the Flex Queue. Queueable, future and scheduled jobs do not. If all 100 Holding slots are full, executeBatch throws a LimitException-style error. Because jobs wait, time-sensitive work (for example a nightly integration) can be starved by long-running jobs ahead of it; use reordering or consolidate jobs. Jobs in Holding are visible through AsyncApexJob (Status = 'Holding') and the FlexQueueItem object, which exposes the position. Aborting a Holding job removes it from the queue.
Code / config example:
// Jobs waiting in the Flex Queue, in position order
List<AsyncApexJob> waiting = [
SELECT Id, ApexClass.Name, CreatedDate
FROM AsyncApexJob
ORDER BY CreatedDate
];
System.debug(waiting.size() + );