Sub topic 6
API limits and error handling
This chapter assumes you can call the REST API with a valid access token, write basic SOQL, and read JSON. It covers the limits Salesforce enforces on API traffic, how to read error responses, and how to design an integration that stays inside those limits and recovers from failures.
Why limits shape integration design
Salesforce is a multitenant platform. Many customers share the same infrastructure, so Salesforce caps how much any one org can consume. The caps are part of the platform's contract. An integration that ignores them works in a demo and fails under production load.
Limits affect three design decisions:
- How many calls you make. Chatty designs that make one call per record run out of daily allowance quickly.
- How you group work. Composite, Batch, and Bulk API 2.0 exist partly to stay within limits.
- How you react to failure. Some errors mean "retry later". Others mean "your request is wrong, so do not retry".
Exact numbers vary by edition, license count, and add-ons, and Salesforce revises them. Treat the figures below as the kinds of limits to check, and confirm the current values in your org.
The main limit types
| Limit type | What it restricts | Typical symptom when exceeded |
|---|---|---|
| Total API requests per 24 hours | Calls across most APIs in a rolling 24-hour window | `REQUEST_LIMIT_EXCEEDED` |
| Concurrent long-running requests | Requests that run longer than a set time at once | `REQUEST_LIMIT_EXCEEDED` or HTTP 503 |
| Query result size and timeouts | Rows returned and time spent per query | `QUERY_TIMEOUT`, or paging with `nextRecordsUrl` |
| Bulk API 2.0 batch allowances | Records and jobs processed per 24 hours | Job rejected or failed |
| Event allocations | Platform event publishes and deliveries per 24 hours | Publish errors or dropped delivery |
| Composite sizes | Subrequests per composite or batch call | `400` with a size message |
The daily request allowance usually scales with edition and the number of user licenses. Sandboxes often have different allowances than production. Bulk API 2.0 and event APIs have their own allowances, separate from the standard request count.
Checking your usage
Call the Limits resource to see the current state of your org.
curl "https://MyDomain.my.salesforce.com/services/data/v60.0/limits" \
-H "Authorization: Bearer $ACCESS_TOKEN"The response is a JSON object. Each limit has a Max and a Remaining value. DailyApiRequests is the one most integrations watch.
Most REST responses also carry a header that reports usage:
Sforce-Limit-Info: api-usage=18/15000The first number is calls used. The second is the allowance. Read this header on each response and you can slow down before you hit the cap, with no extra call needed.
Governor limits are a different thing
Do not confuse API limits with governor limits. Governor limits apply to Apex code that runs inside Salesforce, such as SOQL queries per transaction or DML statements per transaction. API limits apply to calls coming from outside.
The two meet in a few places:
- A REST call that creates a record can fire a trigger. That trigger runs under governor limits. If the trigger exceeds them, the API call fails even though your request was valid.
- An Apex REST endpoint (covered in a later chapter) runs your Apex under governor limits on every call.
- Bulk loads run triggers in chunks, so a trigger that is not bulk-safe can fail a whole chunk.
When you see an error that names a governor limit, such as Too many SOQL queries: 101, the fix is in the Apex code or Flow, not in the client.
Reading error responses
Salesforce REST errors use an HTTP status code plus a JSON body. The body is an array, even when there is one error.
[
{
"message": "Required fields are missing: [LastName]",
"errorCode": "REQUIRED_FIELD_MISSING",
"fields": ["LastName"]
}
]Use errorCode for program logic. The message text is for humans and can change. The fields array tells you which fields are involved when the error relates to specific fields.
Common status codes and what to do
| HTTP status | Typical `errorCode` | Meaning | Retry? |
|---|---|---|---|
| 300 | `MULTIPLE_CHOICES` | The URI matched more than one resource | No, fix the request |
| 400 | `MALFORMED_QUERY`, `INVALID_FIELD` | Bad syntax or unknown field | No |
| 401 | `INVALID_SESSION_ID` | Token expired or revoked | Refresh the token, then retry once |
| 403 | `REQUEST_LIMIT_EXCEEDED`, `INSUFFICIENT_ACCESS` | Limit hit, or no permission | Limit: wait. Permission: no |
| 404 | `NOT_FOUND` | Wrong URL or deleted record | No |
| 409 | `ENTITY_IS_LOCKED`, `UNABLE_TO_LOCK_ROW` | Record locked by another process | Yes, with backoff |
| 415 | `UNSUPPORTED_MEDIA_TYPE` | Wrong `Content-Type` | No |
| 500 | `UNKNOWN_EXCEPTION` | Server-side failure | Yes, limited times |
| 503 | `SERVER_UNAVAILABLE` | Service temporarily unavailable | Yes, with backoff |
The Retry? column is the important one. Retrying a 400 will never succeed and wastes allowance. Retrying a 503 often does.
Note that UNABLE_TO_LOCK_ROW can arrive with different HTTP statuses depending on the API, so base your logic on errorCode first and status second.
Retry strategy
A safe retry policy has four parts.
- Classify the error. Retry only transient errors: locks, timeouts, 5xx, and limit errors after a wait.
- Back off. Wait longer after each failure. Exponential backoff with random jitter avoids many clients retrying at the same instant.
- Cap attempts. Stop after a fixed number of tries and surface the error.
- Make the operation safe to repeat. If a create call times out, you do not know whether the record was created. Retrying could create a duplicate.
For the fourth part, use an external ID field. An upsert against an external ID is idempotent, which means repeating it gives the same result as running it once.
curl -X PATCH \
"https://MyDomain.my.salesforce.com/services/data/v60.0/sobjects/Account/ERP_Id__c/ERP-1001" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"Name": "Acme Corp", "Industry": "Technology"}'If no Account has ERP_Id__c = ERP-1001, Salesforce creates one and returns 201. If one exists, it updates it and returns 204. A retry after a timeout is safe either way. This example assumes you have created an ERP_Id__c field marked as an external ID.
Here is a retry wrapper in Python that applies these rules:
import random
import time
import requests
RETRYABLE_CODES = {"UNABLE_TO_LOCK_ROW", "ENTITY_IS_LOCKED", "SERVER_UNAVAILABLE"}
def call_with_retry(method, url, token, max_attempts=5, **kwargs):
headers = kwargs.pop("headers", {})
headers["Authorization"] = f"Bearer {token}"
for attempt in range(1, max_attempts + 1):
response = requests.request(method, url, headers=headers, timeout=30, **kwargs)
if response.status_code < 400:
return response
try:
error_code = response.json()[0].get("errorCode", "")
except (ValueError, IndexError, KeyError, AttributeError):
error_code = ""
transient = response.status_code >= 500 or error_code in RETRYABLE_CODES
if not transient or attempt == max_attempts:
response.raise_for_status()
delay = min(60, 2 ** attempt) + random.uniform(0, 1)
time.sleep(delay)The function returns on success, raises on permanent errors, and sleeps between transient failures. A 401 is deliberately not retried here. Handle it in your authentication layer by getting a new token and replaying the call once.
Handling the daily request limit
When REQUEST_LIMIT_EXCEEDED appears because of the 24-hour allowance, waiting a few seconds does not help. The window is rolling, so capacity returns gradually. Practical responses:
- Read
Sforce-Limit-Infoand pause non-urgent work when usage passes a threshold you choose, such as 80 percent. - Combine calls. A composite request with up to 25 subrequests counts as one API call toward the daily total for most subrequest types.
- Move large jobs to Bulk API 2.0, which has its own allowance.
- Replace polling with events. Checking "has anything changed?" every minute spends 1,440 calls a day for nothing. Change Data Capture pushes changes to you instead.
- Cache reference data, such as picklist values or record types, that rarely changes.
Partial failures
Many operations return success for some records and failure for others. You must check each result.
A composite request with allOrNone set to false can return HTTP 200 while individual subrequests inside it failed. Each entry in the compositeResponse array has its own httpStatusCode. With allOrNone set to true, a single failure rolls back everything, and the other subrequests report PROCESSING_HALTED.
def failed_subrequests(composite_json):
failures = []
for item in composite_json["compositeResponse"]:
if item["httpStatusCode"] >= 400:
failures.append((item["referenceId"], item["body"]))
return failuresBulk API 2.0 works the same way. A job in state JobComplete can still contain failed rows. Download the failed results and handle them.
curl "https://MyDomain.my.salesforce.com/services/data/v60.0/jobs/ingest/$JOB_ID/failedResults" \
-H "Authorization: Bearer $ACCESS_TOKEN"The response is CSV. It lists each failed row with an sf__Error column. Fix the data and resubmit only those rows.
A decision flow for failures
Common mistakes
- Retrying everything. A malformed query retried five times uses five calls and still fails.
- Trusting HTTP 200. Composite and Bulk responses can hide row-level failures.
- Parsing
messagetext. Match onerrorCodeinstead. - Ignoring row locks in parallel loads. Many threads updating children of the same parent lock that parent. Sort records by parent or lower the concurrency.
- Polling for changes. It burns the daily allowance. Use events.
- Skipping idempotency. Without an external ID, retries create duplicates.
Summary of design rules
- Count calls before you build, and choose the API that uses them efficiently.
- Read limit headers and slow down early.
- Branch on
errorCode, then on status. - Retry only transient errors, with backoff, jitter, and a cap.
- Use external IDs so retries are safe.
- Check every per-record result in composite and bulk responses.
Exercise
Your nightly job upserts 40,000 Contacts by calling the REST API once per record. It fails around record 15,000 with REQUESTLIMITEXCEEDED, and your retry code waits 5 seconds and tries again, several times. Why does the retry not help, and what two changes would you make?
Show answer
The error comes from the rolling 24-hour request allowance, not a short burst, so waiting seconds does not restore capacity. Retrying also spends more calls. Change the design to use Bulk API 2.0 with an upsert operation on an external ID field, which processes the 40,000 rows as one job under its own allowance. Also add a check of the Sforce-Limit-Info header so lower-priority jobs pause before the allowance runs out. Using the external ID also makes any rerun safe.
Exercise
A composite request with allOrNone set to false returns HTTP 200. Your code marks the sync as successful. Later, users report missing Contacts. What went wrong, and how do you fix it?
Show answer
HTTP 200 only means the composite request itself was processed. Each subrequest has its own httpStatusCode inside compositeResponse, and some failed. Loop over compositeResponse, collect entries with httpStatusCode of 400 or higher, log their errorCode values, and retry only the transient ones. If the records must succeed together, set allOrNone to true so a failure rolls back all of them.