Sub topic 14
API Limits and Practical Best Practices
This chapter assumes you can already create, read, and update records with POST, GET, and PATCH. You should also know how to read an error response and when to use Composite sObjects. Here you will learn which limits apply to REST calls and which habits keep an integration reliable.
Limits that apply to REST calls
Salesforce enforces limits per org. Exceeding one makes the API reject your request, so you need to know them before you design a loop that calls the API.
| Limit | What it controls | How you see it |
|---|---|---|
| Daily API request allocation | Total REST and SOAP calls the org can make in 24 hours. The amount depends on edition and license count. | `GET /limits` and the `Sforce-Limit-Info` response header |
| Concurrent long-running requests | Requests that run longer than 20 seconds at the same time. | `REQUEST_LIMIT_EXCEEDED` error |
| Composite sObjects batch size | Up to 200 records per request. | `400` error if you send more |
| Query result page | A query returns a batch of records and a `nextRecordsUrl` when more remain. | `done: false` in the response |
Check the current numbers for your edition in the Salesforce "API Request Limits and Allocations" documentation. Values change between releases, so do not hard-code them.
Checking your remaining allocation
The limits resource reports how much of each limit you have used. This call returns the allocation for the whole org.
curl "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/limits" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN"Look for the DailyApiRequests entry. It has a Max value and a Remaining value. Every API response also carries a Sforce-Limit-Info header such as api-usage=25/15000, so you can track usage without an extra call.
Handling a limit error
When you exceed the daily allocation, Salesforce returns status 403 with the error code REQUEST_LIMIT_EXCEEDED. Retrying immediately does not help, because the allocation resets on a rolling 24-hour window. Retrying is reasonable only for temporary failures such as 503 or a network timeout.
import os
import time
import requests
base = (
f"{os.environ['SF_INSTANCE_URL']}/services/data/"
f"{os.environ.get('SF_API_VERSION', 'v60.0')}"
)
headers = {"Authorization": f"Bearer {os.environ['SF_ACCESS_TOKEN']}"}
def get_with_retry(url, params=None, attempts=4):
for attempt in range(attempts):
response = requests.get(url, headers=headers, params=params, timeout=30)
if response.status_code in (502, 503, 504):
time.sleep(2 ** attempt) # wait 1, 2, 4, 8 seconds
continue
if not response.ok:
# Do not retry 400, 401, 403 or 404. Fix the cause instead.
raise RuntimeError(f"{response.status_code}: {response.text}")
return response
raise RuntimeError("Gave up after repeated temporary failures")
usage = get_with_retry(f"{base}/limits").json()
print(usage["DailyApiRequests"])The function retries only temporary server errors and waits longer after each failure. It raises immediately on client errors, because repeating a bad request wastes allocation.
Practical best practices
- Batch writes. Send up to 200 records in one Composite sObjects call instead of 200 single calls. That uses one request from your allocation instead of 200.
- Request only the fields you need. Use the
fieldsparameter on GET and name columns in SOQL instead of selecting everything. Smaller responses are faster. - Query instead of looping. One SOQL query with a
WHEREclause replaces many single-record GETs. - Page through large results. Follow
nextRecordsUrluntildoneistrue. - Reuse the access token. Request a new one only after a
401, not before every call. - Set timeouts. Always pass a timeout, as the examples do, so a stalled connection does not hang your program.
- Pin the API version. Keep the version in one variable so behavior does not change under you.
- Keep secrets out of code. Read tokens from environment variables or a secret store, and never log them.
Common mistakes
- Treating every error as retryable, which burns allocation on requests that can never succeed.
- Sending single-record calls from inside a loop when a batch or a query would do.
- Ignoring
done: falseon a query, so the program silently processes only the first page. - Hard-coding limit numbers that differ between editions and releases.
Exercise
Your script updates 1,000 Accounts using one PATCH request per record and is close to the daily allocation. How can you reduce the request count, and roughly how many requests would you need?
Show answer
Use the Composite sObjects update endpoint, which accepts up to 200 records per request. 1,000 records need 5 requests instead of 1,000.
Exercise
A call returns status 503. A second call returns 403 with the error code REQUESTLIMITEXCEEDED. Which one should your code retry, and why?
Show answer
Retry the 503 after a short, increasing delay, because it is a temporary server failure. Do not retry the 403, because the daily allocation will not reset until the rolling 24-hour window moves on, and each retry uses more allocation.