APEX-Q11Scenario IntermediateApex & triggers#apex#async-apex

You need to create a user and assign permission sets when a contact is approved. The code fails with a mixed DML error. Why, and what do you do?

Your confidence:Not rated

Model answer

Why: DML on setup objects (User, PermissionSetAssignment, Group membership) and non-setup objects (Contact) in the same transaction isn't allowed, because setup changes affect sharing and access calculations.

Fix

  1. Keep the contact update in the current transaction.
  2. Move user creation and permission set assignment to async: a Queueable (preferred: job ID, objects as input, Finalizer for failures) or a @future method with IDs.
  3. Make it idempotent: check whether the user already exists (by federation ID or username) before creating.
  4. Report failures (for example duplicate username) back to the contact record or a log, because the user won't see an async error.
  5. Tests: wrap setup DML in System.runAs(adminUser) in tests to avoid the same error in test setup.

โœ” Key points to hit

โœ– Red-flag answers

  • Trying to catch the mixed DML exception
  • Doing both in one synchronous transaction with a workaround hack

โ†ช Follow-ups

Which objects count as setup objects?

Objects that affect access: User, Group, GroupMember, QueueSObject, PermissionSet(Assignment), territory assignment objects and a few others. The documentation lists them.

Could Flow avoid the problem?

Flow hits the same rule. Run the user-creation part in a separate transaction, for example a scheduled path in a record-triggered flow, or an asynchronous invocable Apex action.