Sub topic 12
Reducing API Consumption
This chapter assumes you can call the Salesforce REST API with an access token, write basic SOQL, and read the output of the REST Limits resource and the Sforce-Limit-Info header covered earlier. The goal is to lower the number of calls an integration makes without losing data or freshness.
Measure before you optimize
Optimize the biggest consumer first. Use the ApiTotalUsage event logs and the Setup usage pages from earlier chapters to rank callers by volume. Then read that caller's code and sort its calls into the categories below. A job that makes 40,000 single-record calls a day is worth fixing. A script that makes 50 calls a day is not.
Where the waste usually comes from
| Pattern | Typical symptom | Fix |
|---|---|---|
| One call per record | Call count grows linearly with record count | sObject Collections, Composite, or Bulk API |
| Several dependent calls for one task | Create, then query, then update in a row | Composite request |
| Polling for changes | Calls on a timer, mostly returning nothing new | Incremental query, or Change Data Capture |
| Re-reading data that rarely changes | Same describe or picklist call on every run | Caching |
| Retry storms | Spikes of identical failing calls | Backoff, covered in the previous chapter |
| Wide queries | Many pages because of large result sets | Select fewer rows, filter in SOQL |
Batch writes with sObject Collections
The sObject Collections resource creates, updates, or deletes up to 200 records in one request. The request counts as one API call, not 200. Posting 1,000 contacts takes 5 calls instead of 1,000.
import os
import requests
instance_url = os.environ["INSTANCE_URL"]
token = os.environ["ACCESS_TOKEN"]
headers = {"Authorization": f"Bearer {token}"}
def chunks(items, size):
for i in range(0, len(items), size):
yield items[i:i + size]
def create_contacts(rows):
"""Create contacts 200 at a time. Returns a list of (row, errors) failures."""
url = f"{instance_url}/services/data/v60.0/composite/sobjects"
failures = []
for batch in chunks(rows, 200):
body = {
"allOrNone": False,
"records": [{"attributes": {"type": "Contact"}, **row} for row in batch],
}
resp = requests.post(url, json=body, headers=headers, timeout=60)
resp.raise_for_status()
# Results come back in the same order as the records you sent.
for row, result in zip(batch, resp.json()):
if not result["success"]:
failures.append((row, result["errors"]))
return failures
if __name__ == "__main__":
rows = [{"LastName": f"Demo {n}"} for n in range(1000)]
print(f"{len(create_contacts(rows))} failures")Setting allOrNone to False lets good records save while bad ones return an error. Always check each result. The HTTP status is 200 even when some records fail, so raise_for_status() alone hides partial failures.
Combine dependent calls with Composite
A Composite request bundles up to 25 subrequests into one call. Later subrequests can reference earlier results by referenceId, which removes the round trips between dependent steps. Use it when one business action needs several different calls, such as creating an account and a contact that points to it.
curl -s -X POST \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
"$INSTANCE_URL/services/data/v60.0/composite" \
-d '{
"allOrNone": true,
"compositeRequest": [
{
"method": "POST",
"url": "/services/data/v60.0/sobjects/Account",
"referenceId": "newAccount",
"body": { "Name": "Example Co" }
},
{
"method": "POST",
"url": "/services/data/v60.0/sobjects/Contact",
"referenceId": "newContact",
"body": { "LastName": "Rivera", "AccountId": "@{newAccount.id}" }
}
]
}'Collections suit many records of one type. Composite suits a few records of mixed types or steps that depend on each other. Subrequests still run against your per-transaction Apex limits and other platform limits, so a large composite is not free in other ways.
Pull less data: incremental queries
A job that re-downloads every account each hour uses calls on rows that did not change. Filter on SystemModstamp, which updates whenever a record changes, and store the highest value you saw as a checkpoint.
import os
import requests
instance_url = os.environ["INSTANCE_URL"]
token = os.environ["ACCESS_TOKEN"]
headers = {"Authorization": f"Bearer {token}"}
def changed_accounts(since_iso):
"""Yield accounts modified after since_iso, e.g. '2026-11-30T00:00:00Z'."""
soql = (
"SELECT Id, Name, SystemModstamp FROM Account "
f"WHERE SystemModstamp > {since_iso} ORDER BY SystemModstamp"
)
url = f"{instance_url}/services/data/v60.0/query"
params = {"q": soql}
while url:
resp = requests.get(url, headers=headers, params=params, timeout=30)
resp.raise_for_status()
data = resp.json()
yield from data["records"]
url = None if data["done"] else instance_url + data["nextRecordsUrl"]
params = None # nextRecordsUrl already carries the query locator
if __name__ == "__main__":
for account in changed_accounts("2026-11-30T00:00:00Z"):
print(account["Id"], account["Name"])Each page of results is a separate API call. Query pages hold up to 2,000 rows by default, so a result of 10,000 rows costs about 5 calls. Three habits keep this cheap:
- Select only the fields you use. Narrow rows reduce payload size and the chance of hitting heap or timeout problems on the client.
- Fetch related data with relationship queries such as
SELECT Id, Name, (SELECT LastName FROM Contacts) FROM Account, instead of one query per account. - Save the checkpoint only after you have processed a full run. If the job fails midway, you re-read some rows, which is safer than skipping them.
Cache data that rarely changes
Metadata such as object describes, picklist values, and record type IDs changes only when an administrator edits the org. Fetching it on every run wastes calls. A time-based cache is enough for most integrations.
import time
_cache = {}
def cached(key, ttl_seconds, fetch):
"""Return a cached value, calling fetch() only when it is missing or expired."""
now = time.monotonic()
entry = _cache.get(key)
if entry and now - entry[0] < ttl_seconds:
return entry[1]
value = fetch()
_cache[key] = (now, value)
return value
# Example: describe Account at most once an hour per process.
# describe = cached("describe:Account", 3600, lambda: fetch_describe("Account"))An in-process cache disappears when the process restarts. If your integration runs as short-lived jobs, store the cache in a file or a shared store such as Redis. Pick a TTL (time to live) that matches how fast the data can change. A stale picklist value causes an error later, so do not cache anything that changes during normal business use, such as record data used for decisions.
Replace polling with events
Polling asks "anything new?" on a schedule, and most answers are empty. Change Data Capture and Platform Events push changes to subscribers instead. A subscriber connects once and receives events as they happen. This also lowers latency.
Events have their own allocations, such as daily event delivery limits that depend on your edition and licenses. Check them before you move a high-volume integration. Events are not a free replacement, and they add a duty to handle missed events by replaying from a stored replay ID.
Use Bulk API for large volumes
For tens of thousands of records or more, Bulk API 2.0 is the right tool. You upload a CSV, Salesforce processes it asynchronously, and you poll the job status. A job with millions of rows uses very few API calls compared with REST. Bulk jobs have their own daily limits on records and batches, so they move the ceiling but do not remove it.
Choosing an approach
Edge cases and gotchas
- Collections and Composite still hit other limits. Triggers and flows that fire on 200 records run in one transaction with its own governor limits. A batch that saves cleanly at 50 records may fail at 200 with a CPU time error. Lower the batch size if you see that.
- Partial success needs a plan. With
allOrNoneset toFalse, retry only the failed records, and only for errors that can succeed later, such asUNABLE_TO_LOCK_ROW. Do not retry validation errors. - Ordering inside a batch. Do not rely on records being processed in a particular order across separate requests, especially if you split work in parallel.
- Parallel workers. Splitting work across threads can reduce wall-clock time but raises the chance of hitting concurrent request limits and row locks. Fewer, larger requests are better than many small parallel ones.
- Deleted records. An incremental query on
SystemModstampdoes not return hard-deleted rows. Use thequeryAllendpoint to see soft-deleted rows, or subscribe to Change Data Capture delete events.
Exercise
A nightly job updates 5,000 contacts with one PATCH request per record. It runs once a day. How many API calls does it use now, how many with sObject Collections at 200 records per request, and what must the code check on each response?
Show answer
It uses 5,000 calls now. With Collections it uses 25 calls (5,000 / 200). The code must check the per-record result array in each response, because the HTTP status can be 200 even when some records fail when allOrNone is false. Failed records with retryable errors, such as row lock errors, should be retried.
Exercise
An integration queries all Opportunities every 10 minutes and gets back about 6,000 rows each time, but only a few dozen change between runs. Describe two changes that reduce its API usage, and one risk of each.
Show answer
First, filter on SystemModstamp greater than the last checkpoint so each run returns only changed rows. The risk is that hard-deleted records are not returned, so deletions go unnoticed unless you use queryAll or delete events. Second, replace polling with Change Data Capture so Salesforce pushes changes. The risk is that events count against their own allocations and the subscriber must replay missed events from a stored replay ID after downtime.