Concept 1 of 10Synchronous Apex

Synchronous Apex: transactions, order of execution and governor limits

What runs when a record is saved, what a transaction is, and the per-transaction governor limits every design must respect.

Your confidence:Not rated

Simple explanation

Synchronous Apex runs while the user (or API caller) waits: triggers, controllers behind Lightning components, invocable actions called from Flow, and REST or SOAP Apex services.

A transaction is everything that runs from the first entry point until the final commit. All DML in it commits together or rolls back together, and every governor limit is counted per transaction.

Order of execution on save (simplified):

  1. Load the record, apply new values, run system validation.
  2. Before-save record-triggered flows, then before triggers.
  3. System validation again, then custom validation rules, duplicate rules.
  4. Save to the database (not committed yet).
  5. After triggers, assignment and auto-response rules, workflow rules (legacy).
  6. After-save record-triggered flows (and entitlement, escalation and roll-up summary processing).
  7. Commit, then post-commit work: emails, async jobs enqueued in the transaction, platform events published after commit.

Key synchronous limits per transaction:

LimitSynchronousAsynchronous
SOQL queries100200
Rows returned by SOQL50,00050,000
DML statements150150
Rows processed by DML10,00010,000
CPU time10,000 ms60,000 ms
Heap size6 MB12 MB
Callouts100100
Future calls / queueable jobs enqueued50 / 500 in future and batch / 1 from a queueable

Limits change rarely, but check the current Execution Governors and Limits page before quoting edge values βš‘ verify.

Real-world analogy

A transaction is a shopping basket at a self-checkout. You can add and remove items (DML) as you go, but nothing is paid for until you press Pay (commit). If the card is declined (an unhandled exception), the whole basket goes back on the shelves. The store also limits how many items, scans and minutes each basket may use (governor limits), so one customer can't block the shared tills.

Worked example

A Flow updates 200 opportunities in one save. Each opportunity's trigger runs once for the whole chunk of 200, not 200 times. If the trigger queried inside a loop, it would issue 200 queries and fail at query 101:

// βœ– Anti-pattern: a query per record. Fails with "Too many SOQL queries: 101" on a 200-record save.
for (Opportunity opp : Trigger.new) {
    Account acc = [SELECT Id, Industry FROM Account WHERE Id = :opp.AccountId];
}

// βœ” One query for the whole chunk, then a map lookup.
Set<Id> accountIds = new Set<Id>();
for (Opportunity opp : (List<Opportunity>) Trigger.new) {
    accountIds.add(opp.AccountId);
}
Map<Id, Account> accounts = new Map<Id, Account>(
    [SELECT Id, Industry FROM Account WHERE Id IN :accountIds WITH USER_MODE]
);
for (Opportunity opp : (List<Opportunity>) Trigger.new) {
    Account acc = accounts.get(opp.AccountId);
    // ... use acc
}

Diagram

Rendering diagram…

Key points

  • A transaction commits or rolls back as one unit, and limits are counted per transaction.
  • Triggers run once per chunk of up to 200 records, so code must be bulk-safe.
  • Know the order of execution: before-save flows β†’ before triggers β†’ validation β†’ after triggers β†’ after-save flows β†’ commit.
  • Async jobs and emails happen after commit. If the transaction rolls back, they never run.
  • Async contexts get higher limits (200 SOQL, 60 s CPU, 12 MB heap).
  • Use the Limits class to measure consumption, and design for the largest realistic chunk, not one record.

Limits and gotchas

  • Mixed DML: you can't insert setup objects (User, Group membership, permission set assignments) and non-setup objects in one transaction. Move one part to async.
  • Callouts after DML: a callout after uncommitted DML in the same transaction throws an error. Do the callout first or move it to async.
  • Recursion: an after-update trigger that updates the same records fires the trigger again. Guard it (see trigger frameworks).
  • Field updates in workflow rules re-run before and after triggers once more. Legacy automation makes the order harder to reason about; migrate it to Flow.
  • CPU time counts Apex and Flow and validation work in the same transaction. Heavy declarative automation can push code over the limit.

🎀 How to say this in an interview

Interviewers ask "what happens when a record is saved?" to see whether you can reason about where to put logic (before-save flow vs before trigger vs after trigger) and why a deployment failed only with bulk data. Draw the order of execution, then name two limits and how you designed around them.

Common follow-ups

When would you use a before-save flow instead of a before trigger?

For simple field updates on the same record, a before-save flow is fast (no extra DML) and maintainable by admins. Use a before trigger when logic is complex, needs to be unit-tested in Apex, or must share code with other entry points. Don't split the same responsibility across both.

A trigger works in testing but fails on data loads. Why?

Almost always non-bulk code: queries or DML inside loops, or logic that assumes Trigger.new[0]. Data loads send chunks of 200, so the limits are hit. Fix with set-based queries and maps, and test with 200+ records.