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:
- Do the non-setup DML (for example insert Account) in the current transaction.
- Enqueue a Queueable that performs the setup DML (for example insert PermissionSetAssignment).
- 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:
public class AssignPermSetJob implements Queueable {
private List<PermissionSetAssignment> assignments;
public AssignPermSetJob { .assignments = a; }
{
insert assignments;
}
}
insert accounts;
System.enqueueJob( (psas));