# What is the Flex Queue in Salesforce Asynchronous Apex, and how does it manage waiting batch jobs?

**Topic:** Apex · **Difficulty:** Medium · **Tags:** Apex, Asynchronous Apex, Flex Queue

Read it on the site: https://www.forcechallenges.com/interview-questions/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:**
1. `Database.executeBatch(job, size)` is called.
2. If fewer than 5 batch jobs are queued/active (statuses Queued, Preparing, Processing), the job gets a normal slot.
3. Otherwise it goes to the Flex Queue with status `Holding`, ordered first-in, first-out.
4. When a slot frees, the job at the front moves to `Queued`, then `Preparing` and `Processing`.
5. 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:**
```apex
// Jobs waiting in the Flex Queue, in position order
List<AsyncApexJob> waiting = [
    SELECT Id, ApexClass.Name, CreatedDate
    FROM AsyncApexJob
    WHERE Status = 'Holding'
    ORDER BY CreatedDate
];
System.debug(waiting.size() + ' jobs holding');
```

**Hidden gotchas & must-remember points:**
- 5 concurrent batch jobs, 100 Holding jobs: two separate numbers people mix up.
- Only Holding jobs can be reordered; a job already Queued or Processing cannot.
- Flex Queue is FIFO by default, not priority based.
- Chained `executeBatch` calls from `finish()` also land in the Flex Queue if slots are full.
- Holding jobs have not yet run `start()`, so the query has not been evaluated; data changes while waiting are picked up later.
- Before the Flex Queue (Spring 15 era) the over-limit call simply threw an exception.

**Best practice:** Treat the Flex Queue as a safety net, not a scheduler; stagger schedules and merge small jobs so critical batches never wait behind bulk ones.

---
Source: ForceChallenges · last updated 2026-11-02
