Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 36 ยท Getting Started

Execution Model and Governor Limits

Understand Apex transactions, the order of execution and the key governor limits (SOQL, DML, CPU, heap) and how to stay inside them, with Java stand-ins.

Salesforce runs many customers on the same servers. To keep things fair, every Apex transaction has a budget of resources, called governor limits. Go over the budget and Salesforce stops your code with an exception that cannot be caught. Everything done in that transaction is rolled back. Almost every Apex best practice exists because of these limits, so it pays to learn them in your first week.

What is a transaction?

A transaction is one unit of work that either completes fully or not at all. It begins when something starts Apex (a user saves a record, a button is clicked, a web service is called, a scheduled job fires) and ends when all the code that was triggered has finished. If an unhandled error happens anywhere inside, all database changes made in the transaction are rolled back.

flowchart TD
    S["User saves an Account"] --> V["Validation rules"]
    V --> B["Before triggers"]
    B --> W["Save to database<br/>(not yet committed)"]
    W --> AF["After triggers"]
    AF --> FL["Flows and workflow"]
    FL --> C{"Any unhandled error?"}
    C -- "No" --> OK["Commit"]
    C -- "Yes" --> RB["Roll back everything"]

Everything from the first validation to the last flow shares one set of limits.

The limits that matter most

For synchronous Apex (the usual case) the main per-transaction limits are:

Limit Value
SOQL queries issued 100
Records returned by SOQL 50,000
DML statements 150
Records processed by DML 10,000
CPU time 10,000 ms
Heap size 6 MB
Callouts (HTTP requests) 100
Future calls 50

Asynchronous Apex (batch, queueable) gets higher values for CPU (60,000 ms) and heap (12 MB), and the query count is 200. Always check the current official documentation, because Salesforce changes values occasionally.

The important point is that the limits count statements, not rows. One query returning 200 records costs 1 query; 200 queries returning one record each costs 200 and fails.

The classic mistake

This loop runs one query for every account in a list:

Java
for (Account acc : accounts) {
    // BAD: a query inside a loop
    List<Contact> contacts = [SELECT Id FROM Contact WHERE AccountId = :acc.Id];
    System.debug(contacts.size());
}

With 101 accounts, the transaction dies with System.LimitException: Too many SOQL queries: 101. The fix is to query once, outside the loop, for all accounts, then group the results in a map. That technique is called bulkification, and it is central to triggers.

A Java stand-in: a governor

This stand-in counts queries the way the platform does and throws when the limit is hit. We use a limit of 5 to keep output short.

Java Stand-in (Java): a query-limit governor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Checking limits in code

The Limits class tells you how much you have used. This is useful for debugging and for deciding whether to continue or stop gracefully:

Java
System.debug('Queries: ' + Limits.getQueries() + ' of ' + Limits.getLimitQueries());
System.debug('DML rows: ' + Limits.getDmlRows() + ' of ' + Limits.getLimitDmlRows());
System.debug('CPU ms: ' + Limits.getCpuTime() + ' of ' + Limits.getLimitCpuTime());

Per-transaction, not per-class

Limits apply to the whole transaction, not each class. If a trigger calls a helper that calls another class, all of them share the same 100 queries. That is why code that looks fine alone can fail when several pieces run together, for example during a data import that fires many triggers at once.

Governor limits and testing

Each test method gets a fresh set of limits, and you can use Test.startTest() and Test.stopTest() to give the code under test its own fresh budget. Testing Apex covers this later.

Habits that keep you safe

  1. No SOQL or DML inside loops. Collect first, then query or save once.
  2. Query only the fields you need to save heap.
  3. Filter in the query (WHERE) instead of looping in code.
  4. Think in lists: write every method so it handles one record or two hundred equally well.
  5. Move heavy work to async Apex when it is too large for one transaction.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How many SOQL queries may a synchronous transaction issue?

    The synchronous limit is 100 queries per transaction, regardless of how many rows each returns.
  2. 2. What happens when a governor limit is exceeded?

    Limit exceptions cannot be handled with try/catch. The whole transaction is rolled back.
  3. 3. Which code is best for finding contacts of 200 accounts?

    A single query with an IN filter costs one SOQL query. A query inside a loop would cost 200.
  4. 4. Do governor limits apply per class?

    Every class, trigger and flow in the same transaction draws from one shared set of limits.

Summary

  • A transaction is all-or-nothing, and its limits are shared by every piece of code in it.
  • The key synchronous limits are 100 SOQL queries, 150 DML statements, 10,000 DML rows and 10 seconds of CPU.
  • Limits count statements, so never put a query or DML inside a loop.
  • The Limits class shows your current usage.
  • Bulkify your code and move big jobs to asynchronous Apex.

Next: Variables and Data Types