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, and that you have an access token and the SF_INSTANCE_URL, SF_ACCESS_TOKEN, and SF_API_VERSION variables from earlier chapters. Here you learn what the REST API limits, how to see how much of your allowance you have used, and how to write clients that stay inside those limits and recover when a call fails.
What the limits protect
Salesforce is a multitenant platform, so many orgs share the same servers. The limits keep one integration from starving the others. Three limits matter most for the record operations in this tutorial:
| Limit | What it counts | What happens when you exceed it |
|---|---|---|
| Total API requests | Calls made in a rolling 24-hour window. The allowance depends on your edition and license count. | The API returns HTTP 403 with the error code `REQUEST_LIMIT_EXCEEDED`. |
| Concurrent long-running requests | Requests that are still running after about 20 seconds. Production orgs allow more than Developer Edition and trial orgs. | The same `REQUEST_LIMIT_EXCEEDED` error. |
| Per-request size | Records per Composite sObjects call (200) and records per query page (up to 2,000). | The request is rejected, or results arrive in pages. |
The numbers differ between editions and change over time. Treat the table as the shape of the limits, and read your org's actual values from the API (next section) instead of hard-coding them.
Checking your usage
The limits resource reports your allowances and what remains of them.
curl "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/limits" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN"The response is a JSON object with one entry per limit. The entry to watch is DailyApiRequests, which has Max and Remaining values.
Every API response also carries a header called Sforce-Limit-Info. It looks like api-usage=18/15000, meaning 18 requests used out of 15,000. Reading this header costs nothing, because you already made the call. Logging it on every response is the cheapest way to see usage drift upward before it becomes an outage.
A call to limits is itself an API request and counts against the daily total. Poll it occasionally, not before every call.
The cheapest request is the one you do not send
Most limit problems come from too many calls, not from any single call being heavy. Four habits cut the call count.
- Request only the fields you need. The
fieldsquery parameter on a record GET shrinks the response. It does not reduce the request count, but it saves bandwidth and parsing time. - Query instead of looping. If you would otherwise GET 50 records by ID one at a time, one SOQL query with
WHERE Id IN (...)does the same work in one call. - Send only changed fields in a PATCH. Sending unchanged fields wastes bytes and can fire validation rules or triggers on values you did not mean to touch.
- Batch with Composite sObjects. One call can create or update up to 200 records, so 1,000 records take 5 requests instead of 1,000.
Also ask for compressed responses by sending Accept-Encoding: gzip. The requests library does this by default, and curl does it when you add --compressed.
Batching with Composite sObjects
The Composite sObjects collection resource is POST /services/data/<version>/composite/sobjects for creates, and the same URL with PATCH for updates. The body has two parts:
allOrNoneis a boolean. Whentrue, any single failure rolls back the whole call. Whenfalse, records succeed or fail independently.recordsis an array of up to 200 objects. Each object needs anattributesobject with atype, plus the field values. For updates, each record also needs itsId.
The response is an array of results in the same order as the request. Each result has id, success, and errors.
curl -X POST "$SF_INSTANCE_URL/services/data/$SF_API_VERSION/composite/sobjects" \
-H "Authorization: Bearer $SF_ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{
"allOrNone": false,
"records": [
{"attributes": {"type": "Account"}, "Name": "Acme East", "Industry": "Technology"},
{"attributes": {"type": "Account"}, "Name": "Acme West", "Industry": "Banking"}
]
}'With allOrNone set to false, the HTTP status can be 200 even when some records failed. Do not stop at the status code. Check success on every element of the array, as the Python example below does.
The choice between single-record and Composite calls comes down to this:
| Situation | Better choice |
|---|---|
| One record, driven by a user action | Single-record POST or PATCH |
| A few to a few thousand records in one job | Composite sObjects, 200 per call |
| Records that must all succeed or all fail together | Composite with `allOrNone: true` |
| Hundreds of thousands of records or more | Bulk API 2.0, which is built for volume |
A resilient client
The helper below does four things. It logs the usage header, retries temporary server failures with exponential backoff, raises a clear error on an expired session, and stops immediately on a limit error instead of hammering the API. A second function uses it to create accounts in batches of 200 and collect the failures.
import os
import time
import requests
instance_url = os.environ["SF_INSTANCE_URL"]
token = os.environ["SF_ACCESS_TOKEN"]
version = os.environ.get("SF_API_VERSION", "v60.0")
base = f"{instance_url}/services/data/{version}"
headers = {
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
}
RETRYABLE_STATUS = {500, 502, 503, 504}
class SessionExpired(Exception):
pass
class LimitExceeded(Exception):
pass
def log_usage(response):
info = response.headers.get("Sforce-Limit-Info")
if info:
print("usage:", info) # for example: api-usage=18/15000
def request_with_retry(method, url, max_attempts=4, **kwargs):
for attempt in range(1, max_attempts + 1):
try:
response = requests.request(
method, url, headers=headers, timeout=30, **kwargs
)
except (requests.ConnectionError, requests.Timeout):
if attempt == max_attempts:
raise
time.sleep(2 ** attempt)
continue
log_usage(response)
if response.status_code == 401:
raise SessionExpired(response.text)
if response.status_code == 403 and "REQUEST_LIMIT_EXCEEDED" in response.text:
raise LimitExceeded(response.text)
if response.status_code in RETRYABLE_STATUS and attempt < max_attempts:
time.sleep(2 ** attempt)
continue
if not response.ok:
raise RuntimeError(f"{response.status_code}: {response.text}")
return response
def chunks(items, size=200):
for start in range(0, len(items), size):
yield items[start:start + size]
def create_accounts(names):
failures = []
for batch in chunks(names):
body = {
"allOrNone": False,
"records": [
{"attributes": {"type": "Account"}, "Name": name}
for name in batch
],
}
results = request_with_retry(
"POST", f"{base}/composite/sobjects", json=body
).json()
for name, result in zip(batch, results):
if not result["success"]:
failures.append((name, result["errors"]))
return failures
if __name__ == "__main__":
bad = create_accounts([f"Batch Test {n}" for n in range(450)])
print(f"{len(bad)} records failed")Creating 450 accounts takes 3 calls here (200, 200, and 50 records) instead of 450.
Deciding whether to retry
Not every failure deserves a second attempt. Retrying a request that can never succeed wastes your daily allowance, and retrying a limit error makes it worse.
A few details behind the diagram:
- 401 with
INVALID_SESSION_ID. The access token expired or was revoked. Get a new one (for example with a refresh token), then retry the call once. If the new token also fails, stop. - 400 errors. The request itself is wrong, such as
REQUIRED_FIELD_MISSING. Retrying the identical request gives the identical error. UNABLE_TO_LOCK_ROW. Two operations tried to change the same record, or related records, at the same moment. This error is temporary, so a short backoff and retry usually works. It is common when many parallel workers update records under the same parent.- Backoff. Wait longer after each failure (2, 4, 8 seconds), and add a small random delay if several workers run in parallel so they do not all retry at the same instant.
Practical habits for production integrations
- Pin the API version. Put
SF_API_VERSIONin configuration. A version in the URL keeps behavior stable. Upgrade it on purpose and test, instead of silently following the newest release. - Keep secrets out of code and logs. Read tokens from the environment or a secrets store. Log status codes and error codes, not the
Authorizationheader. - Use the instance URL you were given. Do not hard-code a host. The instance URL comes back from the OAuth token response and can change.
- Set a timeout on every call. Without one, a stalled connection can hold a worker forever, and long-running requests count against the concurrent limit.
- Limit parallelism. Running many workers at once is the usual way to hit the concurrent-request limit and row locks. Start with a small number and raise it while watching errors.
- Page through query results. A SOQL response over the page size includes
done: falseand anextRecordsUrl. Request that URL untildoneistrue, and count each page as one API call. - Make writes safe to repeat. Use an upsert by external ID, from the earlier chapter, for jobs that might run twice. A plain POST on retry can create a duplicate.
- Test failures on purpose. Send a record missing a required field, use a bad token, and watch your code take the right branch from the diagram.
Common mistakes
- Looping over single-record calls for thousands of records instead of using Composite sObjects or Bulk API 2.0.
- Treating HTTP 200 from a Composite call as full success when individual records failed.
- Retrying 400 errors, which only spends your allowance.
- Retrying a limit error immediately and in a tight loop.
- Sending batches larger than 200 records to the collections endpoint.
- Using the same access token across many workers with no plan for what happens when it expires.
Exercise
Your script sends a Composite sObjects POST with allOrNone set to false and 200 accounts. The response status is 200, but your script reports "all records created" without looking at the body. What is wrong, and how do you fix it?
Show answer
With allOrNone: false, each record succeeds or fails on its own, so the call can return 200 while some records failed. Read the JSON array in the response and check success on every element. Collect the errors of any element where success is false, and match results to the input by position, because results come back in request order.
Exercise
A job that updates records in 10 parallel workers starts getting errors. Some are REQUEST_LIMIT_EXCEEDED with HTTP 403, and others are UNABLE_TO_LOCK_ROW. Which should the workers retry, which should make them stop, and what change reduces both?
Show answer
Retry UNABLE_TO_LOCK_ROW after a short, randomized backoff, because the lock is temporary. Stop on REQUEST_LIMIT_EXCEEDED and wait for capacity, because retrying immediately uses more of the allowance. Reducing the number of parallel workers lowers both: fewer workers touch the same rows at once, and fewer requests run at the same time. Batching with Composite sObjects also cuts the total request count.
Exercise
You need to update 1,000 Accounts, each with a known ID. How many REST calls does the Composite sObjects approach need at minimum, and how many does the single-record PATCH approach need?
Show answer
Composite sObjects accepts up to 200 records per call, so 1,000 records need 5 calls. Single-record PATCH needs 1,000 calls, one per record.