# How does Asynchronous Apex resolve Mixed DML exceptions involving setup and non-setup objects?

**Topic:** Apex · **Difficulty:** Medium · **Tags:** Apex, Asynchronous Apex, Mixed DML

Read it on the site: https://www.forcechallenges.com/interview-questions/how-does-asynchronous-apex-resolve-mixed-dml-exceptions-involving-setup-and-non-setup-objects

## Answer

**Basics:** Setup objects change security and sharing structure, so Salesforce prevents mixing them with business-data DML in one transaction. The fix is to split the work.

**How it works:**
1. Do the non-setup DML (for example insert Account) in the current transaction.
2. Enqueue a Queueable that performs the setup DML (for example insert PermissionSetAssignment).
3. The queueable runs later in its own transaction, so no mixing occurs.

**Advanced / deep dive:** Common setup objects: User (some field updates are allowed with non-setup DML, but role, profile or active changes are not), Group, GroupMember, QueueSObject, PermissionSet, PermissionSetAssignment, UserRole, and others. Queueable is preferred over `@future` because you can pass complex types, chain, get an Id back, and call it from batch (`@future` cannot be called from batch or future). The trade-off is eventual consistency: the setup change is not visible immediately, so subsequent logic in the original transaction cannot depend on it. In tests, wrap the setup DML in `System.runAs(adminUser)` to avoid the error without async. Flow can hit this error too; Flow's mixing rules follow the same platform constraint, and in Flow you typically use an asynchronous path.

**Code / config example:**
```apex
public class AssignPermSetJob implements Queueable {
    private List<PermissionSetAssignment> assignments;
    public AssignPermSetJob(List<PermissionSetAssignment> a) { this.assignments = a; }
    public void execute(QueueableContext ctx) {
        insert assignments; // setup-object DML isolated in its own transaction
    }
}
// In the main transaction:
insert accounts; // non-setup DML
System.enqueueJob(new AssignPermSetJob(psas)); // setup DML deferred
```

**Hidden gotchas & must-remember points:**
- `@future` cannot be called from batch or future; Queueable can be enqueued from batch `finish` and similar.
- Order matters: the setup DML cannot be undone if the original transaction later fails after enqueue... actually the job is discarded if that transaction rolls back, but a committed job is independent.
- Tests: use `System.runAs` for setup DML.
- Some User field updates are allowed with non-setup DML; role/profile changes are not.
- The error occurs regardless of the order of the DML statements.

**Best practice:** Isolate setup-object DML in its own Queueable and design for eventual consistency.

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