Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 36 ยท Projects and Practice

Practice: Governor Limits, Patterns and Interview Questions

Practise Apex governor limits, bulkification patterns, order of execution and common interview questions, with exercises and a runnable Java limit-meter stand-in.

Salesforce is a multi-tenant platform: many customers share the same servers. To stop one org's runaway code from slowing everyone, the platform enforces governor limits. Almost every Apex interview, certification question and production bug comes back to them. This practice lesson collects the numbers you should know, the patterns that keep you under them, and a set of exercises and interview-style questions to test yourself. It reviews ideas from the whole track, such as bulk-safe triggers, batch jobs and test classes.

Apex runs only in an org. The Apex snippets are read-only; the runnable example is a Java stand-in that counts "queries" the way the governor does, so you can see limits being approached.

Limits to memorise

The figures are per transaction and are the standard values at the time of writing; always check the current release documentation.

Limit Synchronous Asynchronous
SOQL queries 100 200
Records returned by SOQL 50,000 50,000
DML statements 150 150
Records processed by DML 10,000 10,000
CPU time 10,000 ms 60,000 ms
Heap size 6 MB 12 MB
Callouts 100 100
Future calls 50 0 in future, 50 in queueable
Queueable jobs enqueued 50 1

Other numbers worth knowing: 200 records per trigger chunk, 75 percent test coverage, 100 scheduled jobs, 5 concurrent batch jobs, 2,000 as the maximum batch scope, and 5 levels of chained queueables in trial or Developer Edition orgs.

You can read live usage in code with the Limits class:

APEX
System.debug(Limits.getQueries() + ' of ' + Limits.getLimitQueries() + ' queries used');

The core patterns

  1. No SOQL or DML in loops. Query once with WHERE Id IN :ids, build a Map<Id, SObject>, then loop.
  2. Collect, then act. Build a List of changes inside the loop and run one update after it.
  3. Use maps for lookups instead of nested loops.
  4. Query only needed fields and filter in SOQL, not in Apex.
  5. Aggregate in SOQL (COUNT, SUM, GROUP BY) instead of loading rows and adding them up in Apex.
  6. Move heavy work to async (queueable, batch) when it does not need to finish before the user sees the page.
  7. Use Database.update(list, false) when partial success is acceptable.

The classic bug and its fix:

APEX
// Bad: one query per contact
for (Contact c : Trigger.new) {
    Account a = [SELECT Name FROM Account WHERE Id = :c.AccountId];
    c.Description = a.Name;
}

// Good: one query for all
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) { accountIds.add(c.AccountId); }
Map<Id, Account> accounts = new Map<Id, Account>([SELECT Name FROM Account WHERE Id IN :accountIds]);
for (Contact c : Trigger.new) {
    Account a = accounts.get(c.AccountId);
    if (a != null) { c.Description = a.Name; }
}

Order of execution (simplified)

When a record is saved, the platform runs, in order: system validation, before-save record-triggered flows, before triggers, custom validation rules, duplicate rules, the record is saved (not yet committed), after triggers, assignment and auto-response rules, workflow rules, after-save flows, roll-up summary updates, and finally the commit and post-commit work (emails, async jobs). Remember two practical points: field updates made in a before trigger need no extra DML, and an update made in an after-trigger or flow can re-fire triggers, which is why recursion guards exist.

Try the idea: a limit meter (Java stand-in)

Java Stand-in: count queries against a limit (Java)

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.

One record hides the bug; two hundred expose it. That is why triggers must always be tested in bulk.

Exercises

  1. A trigger on Opportunity after update must set a field on the parent Account to the highest amount among its opportunities. Design the queries and DML so 200 opportunities across 50 accounts use a constant number of statements.
  2. A nightly job must update 3 million contacts. Choose the async tool and the scope size, and explain how you avoid duplicate work on a rerun.
  3. An LWC list calls Apex on every keystroke. Describe two changes: debouncing in JavaScript and cacheable=true with @wire.
  4. Make a callout from a trigger safely.
  5. Explain why a test passes with one record but fails with 200.

Write your answers before reading on; solutions are in the summary of ideas below.

  • 1: collect account Ids in a Set, aggregate with SELECT AccountId, MAX(Amount) ... GROUP BY AccountId, update a list of accounts once.
  • 2: Batch Apex with a QueryLocator, scope 200, a filter that excludes already-processed rows.
  • 3: wait 300 ms after the last keystroke before changing the wired parameter; mark the read method cacheable.
  • 4: collect Ids, enqueue one Queueable with Database.AllowsCallouts.
  • 5: a query or DML inside a loop; the limit is only reached in bulk.

Interview-style questions

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the maximum number of records a single trigger invocation handles at once?

    Triggers process records in chunks of up to 200, so handlers must always be written for lists.
  2. 2. How many SOQL queries may a synchronous transaction run?

    The synchronous limit is 100; asynchronous transactions get 200.
  3. 3. Which is the best fix for a SOQL query inside a for loop?

    Bulkify: one query for the whole set and map lookups inside the loop.
  4. 4. Which tool processes millions of records in separate transactions?

    Batch Apex splits work into chunks, each with fresh governor limits.
  5. 5. Why does a before trigger not need a DML statement to save field changes?

    Changes to Trigger.new in a before trigger become part of the pending save.

Summary

  • Governor limits protect a shared platform; know the main numbers and use the Limits class to inspect usage.
  • Bulkify: collect, query once, use maps, update once.
  • Use async tools (future, queueable, batch, schedulable) for volume and callouts.
  • Understand the order of execution and guard against recursion.
  • Practise by designing for 200 records and for millions.

Next: back to the Salesforce Apex and LWC track page