ApexSensei

Blog

Apex Governor Limits: SOQL, DML, CPU

By ApexSensei · · 9 min read

Governor limits in Apex: 100 SOQL queries and 150 DML statements when synchronous. Async raises SOQL to 200, CPU from 10 seconds to 60, and heap to 12 MB.

Apex Governor Limits: SOQL, DML, CPU

Salesforce governor limits cap how much work one Apex transaction can do. They exist because orgs share the same multi-tenant servers. If one transaction runs away, it can slow everyone else down.

Hit a limit and Salesforce stops the transaction with System.LimitException. You cannot catch that exception. The work rolls back.

This page lists the per-transaction Apex limits that show up in real jobs: SOQL, DML, CPU, heap, and callouts. The numbers come from Salesforce's official Execution Governors and Limits documentation (Apex Developer Guide). Do not memorize folklore. Read the table, then write code that stays inside it.

If you want the same patterns with a grader, the matching drills are SOQL in a loop, DML in a loop, one bulk insert, and the async module.

Per-transaction Apex governor limits

These limits reset at the start of each Apex transaction. For Batch Apex, they reset for each execute scope. Scheduled Apex is asynchronous in Setup, but Salesforce applies the synchronous limits to those jobs.

Where the official table lists one number, it applies to both contexts.

Limit Synchronous Asynchronous
SOQL queries issued 100 200
Records retrieved by SOQL 50,000 50,000
Records retrieved by Database.getQueryLocator 10,000 10,000
SOSL queries issued 20 20
Records retrieved by one SOSL query 2,000 2,000
DML statements issued 150 150
Records processed by DML, Approval.process, or Database.emptyRecycleBin 10,000 10,000
Heap size 6 MB 12 MB
CPU time on Salesforce servers 10,000 ms 60,000 ms
Callouts (HTTP or web services) 100 100
Maximum cumulative callout timeout 120 seconds 120 seconds
Methods with the future annotation per invocation 50 0 in batch and future; 50 in Queueable
Apex jobs added with System.enqueueJob 50 1
sendEmail methods 10 10
Maximum execution time for the transaction 10 minutes 10 minutes

Salesforce's notes on that table matter in practice:

  • A parent-child SOQL relationship counts as an extra query. Those queries get a higher cap: three times the top-level SOQL limit.
  • Bulk API transactions use the higher of the two columns. That is why System.enqueueJob in Bulk Apex can use the synchronous cap of 50, not the async cap of 1.
  • CPU time counts Apex, workflow, and validation work on the app server. It does not count time spent in SOQL, DML, SOSL, or waiting on a callout.

The same documentation also lists certified-package limits, static limits, and org-wide async caps. This article stays on the per-transaction table, because that is what a trigger or Queueable job actually hits.

SOQL: one query, then a Map

The failure you see first is Too many SOQL queries: 101. It almost always means a query sat inside a loop.

// Breaks once the list grows.
for (Contact row : contacts) {
    Account parent = [
        SELECT Name
        FROM Account
        WHERE Id = :row.AccountId
    ];
    System.debug(parent.Name);
}

Collect the Ids. Query once. Look up in a Map.

Set<Id> accountIds = new Set<Id>();
for (Contact row : contacts) {
    if (row.AccountId != null) {
        accountIds.add(row.AccountId);
    }
}

Map<Id, Account> accountsById = new Map<Id, Account>([
    SELECT Id, Name
    FROM Account
    WHERE Id IN :accountIds
]);

for (Contact row : contacts) {
    Account parent = accountsById.get(row.AccountId);
    if (parent != null) {
        System.debug(parent.Name);
    }
}

One query. The same shape works for 2 records or 200. That is the drill in Fix a query inside a loop.

DML: one list, one write

DML has the same shape. The cap is 150 statements, not 150 records. update contacts; is one statement for the whole list. update row; inside a loop is one statement per record.

for (Contact row : contacts) {
    row.Title = 'Updated';
}
update contacts;

Records per transaction still cap at 10,000. If you need more than that, you are in Batch Apex territory, not a fatter trigger. Practice the bulk write in Build contacts, then insert once and the repair drill Fix DML inside a loop.

CPU and heap

Synchronous CPU is 10 seconds. Async CPU is 60 seconds. Nested loops over two large lists burn that budget. Build a Map first, then walk one list.

Heap is 6 MB in a synchronous transaction and 12 MB in an async one. Holding 50,000 wide rows in memory is how people hit it. Prefer the fields you need. Clear a list when you are done with it. For huge sets, Database.QueryLocator in Batch Apex is the documented path; a locator in a normal transaction still caps at 10,000 rows.

Measure governor headroom is the drill that makes you read Limits.getQueries() and friends before you guess.

Callouts and async hand-off

You get 100 callouts and 120 seconds of combined timeout. You cannot make a callout after DML in the same transaction. Do the callout first, or move it to a @future(callout=true) method or a Queueable that implements Database.AllowsCallouts.

From a synchronous transaction you can enqueue 50 Queueable jobs. From an async transaction you can enqueue 1. That is why a batch execute should not fan out fifty children. See Queueable Apex and Batch Apex for the job-type choice.

How to read usage while you work

The Limits class reports used and allowed values for the current transaction.

System.debug('SOQL ' + Limits.getQueries() + ' / ' + Limits.getLimitQueries());
System.debug('DML ' + Limits.getDMLStatements() + ' / ' + Limits.getLimitDMLStatements());
System.debug('CPU ' + Limits.getCpuTime() + ' / ' + Limits.getLimitCpuTime());
System.debug('Heap ' + Limits.getHeapSize() + ' / ' + Limits.getLimitHeapSize());

Check before you start another query, not after the 101st. Leave a small buffer if later automation in the same transaction will query too.

A trigger that stays inside the limits

Here is the usual broken after-insert Contact trigger: query the Account per row, insert a Task per row. It dies at 101 queries or 151 DML statements.

public class ContactFollowUp {
    public static void afterInsert(List<Contact> rows) {
        Set<Id> accountIds = new Set<Id>();
        for (Contact row : rows) {
            if (row.AccountId != null) {
                accountIds.add(row.AccountId);
            }
        }

        Map<Id, Account> accountsById = new Map<Id, Account>([
            SELECT Id, Name
            FROM Account
            WHERE Id IN :accountIds
        ]);

        List<Task> followUps = new List<Task>();
        for (Contact row : rows) {
            Account parent = accountsById.get(row.AccountId);
            if (parent == null) {
                continue;
            }
            followUps.add(new Task(
                WhatId = row.AccountId,
                WhoId = row.Id,
                Subject = 'Follow up with ' + parent.Name,
                ActivityDate = Date.today().addDays(7)
            ));
        }
        if (!followUps.isEmpty()) {
            insert followUps;
        }
    }
}

One query. One DML. The same method can take one Contact or a full 200-row trigger batch.

Practice these limits on ApexSensei

Reading the table is step one. The next step is a failing drill.

Those later drills are free to read. Check and Run on them is Apex Path.

Governor limits FAQ

What are Salesforce governor limits?

Governor limits cap how much work one Apex transaction can do, so one org cannot starve the multi-tenant platform. Hit a limit and Salesforce stops the transaction with a System.LimitException.

What is the SOQL query limit in Salesforce?

A synchronous Apex transaction can issue 100 SOQL queries. An asynchronous transaction (Batch Apex or a future method) can issue 200. Both can retrieve 50,000 SOQL rows. Scheduled Apex uses the synchronous limits.

Do async Apex transactions get different governor limits?

Some do. SOQL queries rise from 100 to 200, heap from 6 MB to 12 MB, and CPU time from 10,000 ms to 60,000 ms. DML stays at 150 statements and 10,000 rows. You can enqueue 50 Queueable jobs from a synchronous transaction, and only one from an asynchronous transaction.

How do you avoid hitting governor limits?

Query and write once, not once per record. Collect Ids, run one SOQL, store results in a Map, then do one DML list. If the work is large, move it to Queueable or Batch Apex so each chunk gets a fresh async limit set.

What happens when Apex hits a governor limit?

Salesforce throws an uncatchable System.LimitException and rolls back the transaction. You cannot catch it in a try/catch. The Limits class lets you check usage before you start more work.

Where can I practice governor-safe Apex?

ApexSensei has drills for SOQL in a loop, DML in a loop, one bulk insert, governor headroom, and async jobs. The first two modules are free to run. The rest are free to read.

Practice Apex free on ApexSensei