# Async Apex — limits, Queueable, Cursors, Batch

Target: Spring '26 (API 66.0). Sources: [Execution Governors and Limits](https://developer.salesforce.com/docs/atlas.en-us.salesforce_app_limits_cheatsheet.meta/salesforce_app_limits_cheatsheet/salesforce_app_limits_platform_apexgov.htm), [AsyncOptions](https://developer.salesforce.com/docs/atlas.en-us.apexref.meta/apexref/apex_class_System_AsyncOptions.htm), [Apex Cursors](https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_cursors.htm).

## Per-transaction limits — synchronous vs asynchronous

| Limit | Synchronous | Asynchronous (Batch, Queueable, future, scheduled) |
|---|---|---|
| SOQL queries | 100 | 200 |
| Query rows | 50 000 | 50 000 |
| SOSL queries | 20 | 20 |
| DML statements | 150 | 150 |
| DML rows | 10 000 | 10 000 |
| CPU time | 10 000 ms | 60 000 ms |
| Heap | 6 MB | 12 MB |
| Callouts | 100 | 100 |
| Callout timeout (cumulative) | 120 s | 120 s |
| Queueable jobs enqueued per transaction | 50 | 1 from a running Queueable (chain) |

Only SOQL, CPU and heap grow in async. DML limits do not — "async doubles most" is wrong.

## Queueable with AsyncOptions and Finalizer

```apex
public with sharing class OrderSyncQueueable implements Queueable, Database.AllowsCallouts, Finalizer {
    private final Id accountId;
    private final Integer attempt;

    public OrderSyncQueueable(Id accountId) { this(accountId, 1); }
    private OrderSyncQueueable(Id accountId, Integer attempt) { this.accountId = accountId; this.attempt = attempt; }

    public void execute(QueueableContext ctx) {
        System.attachFinalizer(this);
        ErpClient.pushOrders(accountId);            // callout first, then DML
    }

    public void execute(FinalizerContext ctx) {
        if (ctx.getResult() == ParentJobResult.UNHANDLED_EXCEPTION && attempt < 3) {
            System.enqueueJob(new OrderSyncQueueable(accountId, attempt + 1));
        } else if (ctx.getResult() != ParentJobResult.SUCCESS) {
            Logger.error('OrderSync failed', ctx.getAsyncApexJobId(), ctx.getException());
        }
    }

    public static void enqueueOnce(Id accountId) {
        AsyncOptions options = new AsyncOptions();
        options.MaximumQueueableStackDepth = 5;
        options.MinimumQueueableDelayInMinutes = 1;
        options.DuplicateSignature = QueueableDuplicateSignature.Builder()
            .addId(accountId).addString('OrderSync').build();
        try {
            System.enqueueJob(new OrderSyncQueueable(accountId), options);
        } catch (DuplicateMessageException e) {
            // identical signature already queued; nothing to do
        }
    }
}
```

`QueueableDuplicateSignature.Builder()` accepts `addId`, `addInteger`, `addString`; the signature is scoped to the org and lasts until the queued job finishes. `Logger` is the project's logging class.

## Apex Cursors (GA Spring '26) — resumable large read

```apex
public with sharing class ContactArchiveQueueable implements Queueable {
    private final Database.Cursor cursor;
    private Integer position;

    public ContactArchiveQueueable() {
        this(Database.getCursor('SELECT Id, Email FROM Contact WHERE LastActivityDate < LAST_N_DAYS:730'), 0);
    }
    private ContactArchiveQueueable(Database.Cursor cursor, Integer position) {
        this.cursor = cursor; this.position = position;
    }

    public void execute(QueueableContext ctx) {
        List<Contact> chunk = cursor.fetch(position, 2000);
        ArchiveService.archive(chunk);                       // idempotent
        position += chunk.size();
        if (position < cursor.getNumRecords()) {
            System.enqueueJob(new ContactArchiveQueueable(cursor, position));
        }
    }
}
```

- `Database.getCursor(soql)` / `Database.getCursorWithBinds(soql, binds, accessLevel)`; `fetch(position, count)` returns up to 2 000 rows; `getNumRecords()` is the total.
- Limits: 50 M rows per cursor, 10 `fetch` calls per transaction, 10 000 cursors per day, 100 M rows per day; fetched rows count against the SOQL row limit and each `fetch` counts as a query.
- Choose Cursors over Batch when the work is a large *read* traversal with idempotent per-chunk processing and no cross-chunk state. Choose Batch when each chunk must be its own transaction with `Database.Stateful` accumulation, or when the org already schedules and monitors batches.

## Batch Apex rules

- `Database.Batchable<SObject>` with a `Database.QueryLocator` for up to 50 M rows; `Iterable` for custom sources (50 000 rows).
- `execute` is idempotent; scope ≤ 200 when callouts are involved (100-callout limit per scope); `Database.Stateful` only for counters you report in `finish`.
- Never chain a batch from `execute`; from `finish` only. One `Schedulable` whose `execute` does nothing but enqueue.
- Monitor: Setup → Apex Jobs; alert on `Failed` and on `Holding` queue growth (Apex Flex Queue holds 100 jobs).

## Choosing

| Need | Use |
|---|---|
| Post-commit work, callouts from a trigger, chaining, dedupe | Queueable + `AsyncOptions` |
| Retry/cleanup after a Queueable fails | Finalizer |
| Large read traversal, resumable, no per-chunk transaction | Apex Cursors from a Queueable |
| Each chunk needs its own transaction and stateful roll-up | Batch Apex |
| Run on a schedule | Schedulable that enqueues a Queueable or Batch |
| Cross-system decoupling | Platform Event + subscriber (see `salesforce-integration`) |
| Legacy only | `@future` — do not write new ones |
