Sub topic 1
Why Governor Limits Exist
Prerequisites
This chapter assumes you can already do the following:
- Read and write basic Apex: classes, methods, variables, loops and conditionals.
- Use the collections
List,SetandMap. - Write simple SOQL queries and run DML statements (
insert,update,delete). - Recognize an Apex trigger and the difference between
beforeandafterevents.
You don't need to know any limit values yet. This chapter explains the reason limits exist and how they behave. Later chapters cover specific limits and the code patterns that stay within them.
The problem: many customers, one set of servers
Salesforce is a multitenant platform. A tenant is one customer org. Many orgs, often thousands, share the same physical infrastructure: the same application servers, the same database instance, and the same pool of CPU and memory. Each org has its own data, which is kept logically separate. The hardware underneath is shared.
Shared hardware creates a risk. Apex is a real programming language, and it runs inside that shared environment. A single piece of careless Apex could do any of these:
- Run an infinite loop that consumes a CPU core.
- Query millions of rows and hold them in memory.
- Send thousands of database writes in one burst.
- Hold a database connection open for minutes.
On a server you own, a program like that only hurts you. On a shared platform, it would slow down every other org on the same instance. Customers who did nothing wrong would see timeouts and slow pages.
Salesforce handles this with governor limits. A governor limit is a hard cap on a resource that one Apex transaction may consume. The runtime counts resource use as your code runs. If a count passes its cap, the runtime stops your transaction.
The name comes from a mechanical governor, a device that stops an engine from running past a safe speed.
The diagram shows where the check sits. It is not a one-time review before your code starts. The runtime checks as the code executes, so a transaction can run fine for a while and then be stopped partway through.
What a limit looks like in practice
Run the following in the Developer Console's anonymous Apex window (Debug, then Open Execute Anonymous Apex):
for (Integer i = 0; i < 101; i++) {
List<Account> sample = [SELECT Id FROM Account LIMIT 1];
}
System.debug('Finished all 101 queries');The loop works for the first 100 iterations. On the 101st query, the transaction fails with this error:
System.LimitException: Too many SOQL queries: 101The final debug line never runs. Three points about this failure matter for everything that follows:
- It is a
System.LimitException. You can writecatch (Exception e)and it will not catch this one. Salesforce deliberately makes limit exceptions uncatchable, because letting your code swallow them and continue would defeat the purpose of the limit. - The whole transaction rolls back. Any records inserted or updated earlier in the same transaction are undone. The user sees an error and nothing is saved.
- The loop could not have been logic-correct and still safe. Nothing in the code is wrong in a general-purpose sense. Each query is valid. The problem is only the count of queries.
This is why governor limits feel unusual to developers coming from other platforms. Code that is correct in terms of logic can still be unacceptable in terms of resource use.
What counts as a transaction
A limit is measured per transaction, so you need to know what a transaction is. In Apex, a transaction is one unit of work that starts with an entry point and ends when the work either commits or rolls back. Entry points include:
- A user saving a record through the UI, which fires triggers, flows and validation.
- An API call that inserts or updates records.
- A Lightning component calling an
@AuraEnabledmethod. - A scheduled job, a Queueable job, or one
executecall of a Batch job. - An anonymous Apex execution.
Everything triggered inside that unit of work shares one set of counters. This includes:
- Your trigger.
- Any class the trigger calls.
- Other triggers fired by DML that your code performs.
- Flows and workflow field updates that run as part of the save.
Consider a user who updates one Account. A trigger on Account runs and updates its Contacts. A trigger on Contact then runs and queries Cases. All of that work draws from the same pool of SOQL queries, DML statements and CPU time.
A trigger you wrote and tested alone can therefore fail in production. Another trigger, a flow or a managed package in the same transaction may have already used part of the budget. Keeping your own usage low is the only reliable way to leave room for everything else.
The main resources that are capped
Salesforce limits many resources. This chapter only introduces the categories, and the next chapter looks at the main ones in detail. The values below are for synchronous Apex at the time of writing.
| Resource | Synchronous limit | What it protects |
|---|---|---|
| SOQL queries issued | 100 | Database connections and query load |
| Records returned by SOQL | 50,000 | Database reads and memory |
| DML statements issued | 150 | Database write operations |
| Records processed by DML | 10,000 | Database writes |
| CPU time | 10,000 ms | Application server processors |
| Heap size | 6 MB | Application server memory |
Asynchronous Apex (Queueable, Batch, @future, scheduled jobs) gets larger allowances for some resources. For example, CPU time is 60,000 ms and heap is 12 MB. The SOQL query count is 200. Heavy work belongs there, a topic a later chapter covers.
The table shows that each limit maps to something physical. SOQL and DML caps protect the database, which is the hardest resource to scale because every tenant on the instance writes to it. CPU and heap caps protect the application servers. Limits also exist on callouts, email sends, future calls and other features, and the reasoning is the same.
Why limits are per transaction, not per day or per org
Salesforce could have chosen a different approach, such as a daily allowance of queries per org. It chose per-transaction caps for several reasons.
- Predictable cost per request. A transaction runs for a bounded time and uses bounded memory. The platform can schedule thousands of these across shared servers without worrying that one will run for an hour.
- Fast failure. Without per-transaction limits, one bad loop could run until a timeout. A limit stops it in seconds, close to the line that caused the problem.
- Fairness without coordination. Each transaction is checked on its own. The platform doesn't need to track and balance usage across tenants in real time.
- Pressure toward efficient code. Developers who cannot run 5,000 queries must find a better way. Usually the better way (one query, a
Map, one DML statement) is also faster everywhere else.
A few limits do apply across a longer period. Examples are daily API request totals, async Apex executions over 24 hours and email sends. This tutorial focuses on the per-transaction limits, because they are the ones that cause most Apex failures.
Why this changes how you design Apex
Governor limits and bulk behavior are tied together. Salesforce does not process only one record at a time. Data loads, API calls, batch jobs and integrations deliver records in groups. A trigger can receive up to 200 records in one invocation.
Compare these two thoughts:
- "My trigger runs one query." That sounds safe.
- "My trigger runs one query per record, and it may receive 200 records." That is 200 queries, which is over the limit of 100.
The same trigger passes when a user edits one record in the UI. It fails when an admin loads 200 records with Data Loader. This is the most common limit failure in real orgs. It is hard to catch because everything passes during manual testing.
The practical rule is this: write every piece of Apex as if it will always receive a full batch of records. Doing so is called bulkification. Later chapters build the techniques, which include moving queries out of loops, collecting records and running DML once, and testing with 200 records.
Common misunderstandings
"I can catch the exception and recover." You can't. A LimitException is not catchable, and the transaction is terminated. You can only avoid it, using the checks the Limits class provides (covered in a later chapter).
"My org is small, so limits don't affect me." Limits are the same for every org, large or small, in a given edition and context. A small org with a data load will hit the same caps as a large one.
"The test passed, so the code is safe." Test methods that insert one record verify the logic but not the bulk behavior. A test needs to push a full batch through the code to prove it is safe. You will write such tests later in the tutorial.
"Limits are a flaw in the platform." They are a deliberate design trade-off. The platform gets a low price per customer and consistent performance. In exchange, developers accept a smaller resource budget. Developers who treat limits as a design input write code that is faster and cheaper to run.
Summary of the model
Keep this working model in mind for the rest of the tutorial:
- Many orgs share one platform instance, so Salesforce must prevent any one of them from using too much.
- The runtime enforces this with hard caps on resources, counted per transaction as the code runs.
- Exceeding a cap throws an uncatchable
System.LimitExceptionand rolls the whole transaction back. - All automation in one save shares the same counters, so your code must leave room for the rest.
- Because triggers and APIs deliver records in batches, code that works for one record can still fail at scale.
Exercise
A trigger on Contact queries its parent Account inside a for loop over Trigger.new. It works when a user saves one Contact in the UI. An admin then imports 150 Contacts with Data Loader in a single batch of 150 records, and the import fails with Too many SOQL queries: 101. Explain why the failure appears only during the import, and why wrapping the query in try/catch would not fix it.
Show answer
The loop runs one query per Contact. With one Contact, the trigger uses 1 query, far below the limit of 100. With 150 Contacts in one transaction, the trigger tries to run 150 queries, and the 101st query exceeds the limit of 100 for synchronous Apex. A try/catch does not help because System.LimitException cannot be caught. The transaction is terminated and rolled back. The fix is to query once outside the loop, which later chapters cover.
Exercise
Name two reasons Salesforce measures governor limits per transaction instead of giving each org a daily allowance only. Then explain why a trigger that stays at 60 of 100 SOQL queries can still be a problem.
Show answer
Per-transaction limits make the cost of each request bounded and predictable, and they stop a runaway loop within seconds instead of letting it run until a timeout. They also need no real-time coordination between tenants, because each transaction is checked on its own. A trigger that uses 60 queries is a problem because the counters are shared by everything that runs in the same transaction, including other triggers, flows and managed packages. Only 40 queries remain for all of them, so another automation can push the transaction over the limit.