Sub topic 6
API limits and error handling
This chapter assumes you can already call the REST API with an access token and read short Python and JSON snippets. Limits and errors affect which API you choose, because each API spends a different budget.
The limits that shape integrations
Salesforce is multitenant, so it caps how much each org can consume. Three kinds of limit matter most:
- Daily API requests. A rolling 24-hour total. The size depends on your edition and license count.
- Concurrent long-running requests. Production orgs allow only a small number of requests that run 20 seconds or longer at the same time.
- Per-API allocations. Bulk API 2.0 has daily caps on batches and records. Platform Events have their own publish and delivery allocations. A Composite request can hold up to 25 subrequests.
Composite and Bulk API 2.0 help because they move many records per request. One Composite call with 25 subrequests counts as one API request.
Checking your usage
The limits resource reports what is left. Look at DailyApiRequests.
curl -s "https://MyDomain.my.salesforce.com/services/data/v60.0/limits" \
-H "Authorization: Bearer $ACCESS_TOKEN"Most REST responses also carry a Sforce-Limit-Info: api-usage=used/max header. Log it so you can see consumption climb before it becomes an outage.
Reading error responses
A failed REST call returns an HTTP status and a JSON array of error objects:
[
{
"message": "Required fields are missing: [LastName]",
"errorCode": "REQUIRED_FIELD_MISSING",
"fields": ["LastName"]
}
]Branch on errorCode, not on the message text.
| Status | Typical cause | Response |
|---|---|---|
| 400 | Bad JSON, bad SOQL, validation failure | Fix the request. Do not retry. |
| 401 | `INVALID_SESSION_ID`, the token expired | Refresh the token, then retry once. |
| 403 | `REQUEST_LIMIT_EXCEEDED` or insufficient access | Stop for limits. Fix permissions otherwise. |
| 404 | `NOT_FOUND`, the record or resource is missing | Check the Id and the URL. |
| 500, 503 | Temporary server trouble | Retry with backoff. |
A retry wrapper
This function retries only the failures that can succeed on a second attempt.
import time
import requests
RETRYABLE = {500, 502, 503, 504}
def call(method, url, token, refresh, retries=4, **kwargs):
refreshed = False
for attempt in range(retries):
resp = requests.request(
method,
url,
headers={"Authorization": f"Bearer {token}"},
timeout=30,
**kwargs,
)
if resp.status_code < 400:
return resp
if resp.status_code == 401 and not refreshed:
token = refresh()
refreshed = True
continue
errors = resp.json() if resp.content else []
codes = [e.get("errorCode") for e in errors if isinstance(e, dict)]
if "REQUEST_LIMIT_EXCEEDED" in codes:
raise RuntimeError("API limit reached; stop and wait")
if resp.status_code in RETRYABLE:
time.sleep(2 ** attempt)
continue
resp.raise_for_status()
raise RuntimeError("Retries exhausted")Designing around limits
- Batch work with Composite, or use Bulk API 2.0 for large volumes.
- Cache reference data instead of querying it on every call.
- Use Change Data Capture or Platform Events instead of polling for changes.
- Check
limitsbefore starting a large job. - With Composite and
allOrNoneset totrue, one failed subrequest rolls back the rest. Inspect each subresponse for its own error.
Exercise
Your integration gets a 403 response with errorCode REQUESTLIMITEXCEEDED. Should it retry after one second with exponential backoff? Give a reason and name one design change that reduces the problem.
Show answer
No. The limit is a budget, not a brief glitch, so quick retries only spend more of it. Stop and wait, or alert someone. To reduce the problem, replace polling with Change Data Capture, or batch records with Composite or Bulk API 2.0.