Sub topic 1
Why Salesforce has limits
Salesforce enforces limits on API calls, Apex code, and long-running requests. This chapter explains the reasoning behind them. If you know why they exist, you can predict which limit a design will hit before you build it. Later chapters cover each limit in detail and show how to monitor it.
Prerequisites
This chapter assumes you have:
- Basic familiarity with Salesforce orgs, objects, and editions.
- Experience making HTTP requests to a REST API.
- Basic SOQL knowledge.
- Basic ability to read Apex code.
You don't need to have hit a limit error yet. If you have, the examples below will probably look familiar.
The shared platform model
Salesforce is a multitenant platform. Many customers, called tenants, run on the same infrastructure. Each customer's org is a logical partition. Customers share application servers, databases, and network capacity. Their data is separated by org ID, not by dedicated hardware.
This model has real benefits. Salesforce can ship upgrades to everyone at once, run one codebase, and keep costs low per customer. The cost is that one tenant can affect the others. A tenant that runs an unbounded query or a runaway integration uses capacity that other tenants also need.
Limits are how Salesforce protects the shared resource. Two ideas sit behind them:
- Fairness. No single org should be able to take a disproportionate share of the shared database, CPU, or memory.
- Predictability. Salesforce can plan capacity and promise performance only if each org's maximum consumption is bounded.
A shared apartment building is a useful comparison. Every unit has its own meter, and every unit has a cap on the building's water pressure. One tenant can't drain the supply for the rest. The comparison is only an aid. In Salesforce the caps are numbers you can read and monitor.
What limits protect
Each kind of limit protects a different resource. It helps to match them up.
| Resource being protected | Typical limit | Where it applies |
|---|---|---|
| Request volume over time | Daily API request limit | The whole org, over a rolling 24 hours |
| Server threads | Concurrent long-running request limit | The whole org, at one moment |
| Database and CPU per unit of work | Apex governor limits | A single Apex transaction |
Chapter 2 covers these categories properly. For now, notice the pattern. The limits cover three different scopes: a long period, a single moment, and a single transaction. Each scope catches a different kind of misuse. A daily cap can't stop one runaway query, and a per-transaction cap can't stop a script that makes millions of small calls.
Limits are a design input
Developers often treat limits as obstacles to work around late in a project. This leads to a familiar sequence. The code works in a sandbox with 20 records, then fails in production with 20,000. The error appears under load, usually after a data import, a new integration, or a busy month-end.
A better approach treats limits as design requirements, in the same way you treat latency or storage. Ask these questions early:
- How many API calls will this integration make per day at expected volume, and at peak volume?
- Does a single user action trigger one transaction, or several chained ones?
- Which other systems share the same org's limits?
The third question matters most. The daily API limit belongs to the org. Every integration, middleware tool, data loader, and mobile app that calls the API draws from the same pool. A new integration that looks cheap can still use up headroom that another team's integration needed.
A concrete example: governor limits
Apex governor limits are the most visible case of limits protecting shared resources. Apex code runs on servers that other tenants also use. So Salesforce caps what one transaction can consume. In synchronous Apex, the common caps are:
- 100 SOQL queries per transaction.
- 150 DML statements per transaction.
- 10,000 ms of CPU time.
- 6 MB of heap size.
Asynchronous Apex such as Batch Apex and @future methods gets higher ceilings for some of these. The current values are in Salesforce's Apex Developer Guide, and they can change between releases. Your code should read the live values with the Limits class instead of hard-coding numbers. Chapter 6 covers that class.
The following code shows why these limits exist. It runs one query per account, so it fails as soon as the account list is large.
// Anti-pattern: one SOQL query inside a loop.
List<Account> accounts = [SELECT Id FROM Account LIMIT 200];
for (Account a : accounts) {
List<Contact> contacts = [SELECT Id FROM Contact WHERE AccountId = :a.Id];
System.debug(a.Id + ': ' + contacts.size());
}If the org has at least 101 accounts, this code throws System.LimitException: Too many SOQL queries: 101 on the 101st query. A LimitException can't be caught with try/catch. The transaction ends and all its changes roll back.
The fix is to ask the database for all the data in one query. A relationship subquery does this:
// One query returns accounts and their contacts together.
List<Account> accounts = [
SELECT Id, (SELECT Id FROM Contacts)
FROM Account
LIMIT 200
];
for (Account a : accounts) {
System.debug(a.Id + ': ' + a.Contacts.size());
}This version uses one query whether there are 5 accounts or 200. The change is about more than avoiding an error. It also reduces the load on the shared database, which is the reason the limit exists.
What the REST API limits look like from outside
Limits also apply to code that runs outside Salesforce. Each call to the REST, SOAP, or Bulk API counts toward the org's daily API request allocation. Each call also takes a server thread while it runs. Long-running calls, such as a slow report or a heavy query, are counted separately because they hold threads for a long time.
You can see the allocation yourself by calling the Limits resource. This is the same call used in chapter 7, shown here only to make the idea concrete.
curl -s -H "Authorization: Bearer $ACCESS_TOKEN" \
"$INSTANCE_URL/services/data/v60.0/limits"
# The response is a JSON object keyed by limit name. For example:
# { "DailyApiRequests": { "Max": 15000, "Remaining": 14980 }, ... }The numbers above are illustrative. The real Max depends on your edition, your license count, and any add-on purchases. A Developer Edition org has a much smaller allocation than a large Enterprise org, so a script that is fine in one can break in the other.
Common misunderstandings
These mistakes come up often when people first work with limits.
"Limits are a punishment or a billing device"
Limits aren't mainly about revenue. Some allocations scale with your edition and licenses, so they correlate with what you pay. But the main purpose is protecting a shared system. That is why a limit that exists for technical reasons, such as the per-transaction query cap, is the same regardless of how much you pay.
"My org is small, so I won't hit them"
Small orgs hit limits regularly. A single integration that polls every few seconds can use a Developer Edition allocation in hours. A trigger with a query in a loop fails the first time someone loads a few hundred records. Size matters less than design.
"The daily limit resets at midnight"
The daily API limit is a rolling 24-hour window, not a calendar day. Usage from 10 a.m. yesterday stops counting at 10 a.m. today. Resetting at a fixed time would let a client burn the full allocation at 11:59 p.m. and again at 12:01 a.m. A rolling window prevents that spike. It also means that after you hit the limit, capacity returns gradually, not all at once.
"One limit protects everything"
Staying under the daily API limit doesn't protect you from governor limits, and the reverse is also true. An integration can make only 500 API calls a day and still fail, because each call triggers Apex that exceeds the CPU limit. Monitor each scope separately.
Failure modes to expect
Knowing why limits exist helps you predict how they fail:
- Hard stops. When you hit a daily or concurrency limit, the platform rejects new requests with an error. For the daily limit that error is
REQUEST_LIMIT_EXCEEDED. It does not slow you down gradually. Everything that shares the org's allocation is affected at once. - Rollback. A governor limit exception undoes the whole transaction, including work done before the limit was reached. Partial success is not available.
- Shared blast radius. Because the daily allocation belongs to the org, one noisy integration can break unrelated ones. The failing system is often not the one that caused the problem.
- Late discovery. Limits show up under production load, not in tests with small data sets. Without monitoring, the first sign is often a user complaint.
These failure modes are the reason the rest of this tutorial focuses on monitoring. You can't tune what you can't see, and you want to see consumption before the error appears.
Where this fits in the tutorial
The remaining chapters build on this model:
- The main kinds of limits, then the daily API request limit, concurrent requests, and governor limits in detail.
- Reading usage from the Apex
Limitsclass, the REST Limits resource, and theSforce-Limit-Inforesponse header. - Monitoring in Setup, and finding who uses the API with Event Monitoring.
- Handling
REQUEST_LIMIT_EXCEEDED, reducing consumption, and building threshold alerts.
Keep the main idea from this chapter as you read them. Each limit exists to keep one tenant's workload from harming the others, and each is easier to live with when you design for it from the start.
Exercise
An integration team says, "We only make 2,000 API calls a day, and our org's allocation is 100,000, so we can't cause problems for anyone." Give two reasons this reasoning might still be wrong.
Show answer
First, the daily allocation belongs to the org and is shared by every integration, data loader, and app that calls the API. Other systems may already use most of the 100,000, so 2,000 calls could be the ones that push the org over the limit. Second, API call count is only one scope. Each call may run Apex that exceeds governor limits such as CPU time or SOQL queries, and it may be a long-running request that counts against the concurrent request limit. A low call count doesn't guarantee low resource use per call.
Exercise
Why is the daily API request limit a rolling 24-hour window instead of resetting at a fixed time each day, and what does that mean for recovery after you hit it?
Show answer
A fixed reset would let a client use the full allocation just before the reset and again just after it, creating a spike of double the intended load in a short time. A rolling window counts requests from the previous 24 hours at every moment, so usage can't be concentrated that way. After you hit the limit, capacity returns gradually as old requests age out of the window, not all at once at a set time.
Exercise
A trigger passes testing with 10 records but throws "Too many SOQL queries: 101" in production during a data load. What is the likely cause, and why can't you fix it with try/catch?
Show answer
The trigger probably runs a SOQL query inside a loop over the records, so the query count grows with the record count and passes 100 once a batch has more than 100 records. A LimitException can't be caught with try/catch, because the platform ends the transaction and rolls it back. The fix is to bulkify the code: query once outside the loop, using a collection of IDs or a relationship subquery, and then process the results in memory.