Sub topic 12
Reducing API Consumption
This chapter assumes you can call the Salesforce REST API, write basic SOQL, and read Apex. You have already seen how to measure usage with the Limits resource, the Sforce-Limit-Info header, and ApiTotalUsage logs. Here you use that data to lower the number of calls an integration makes.
Start with the measurements
Cutting calls without data wastes effort. First find the top consumers. The ApiTotalUsage event logs show which users, connected apps, and clients make the most calls. Fix the largest source first, because a single polling job often accounts for most of the daily total.
Four common techniques
| Technique | What it replaces | Effect on API calls |
|---|---|---|
| Batching | Many single-record requests | One request carries many records |
| Bulk operations | Row-by-row loads of large data sets | Thousands of records per batch |
| Caching | Repeated reads of data that rarely changes | Reads served locally |
| Event-driven design | Polling for changes | Calls happen only when something changes |
Batch requests
The sObject Collections resource lets one request create, update, or delete up to 200 records. The composite resource can combine several different operations in one call, and each subrequest still counts toward Apex and platform limits but the HTTP request counts once toward the API total.
The example below updates 200 records with one call instead of 200.
import os
import requests
instance_url = os.environ["INSTANCE_URL"]
token = os.environ["ACCESS_TOKEN"]
records = [
{"attributes": {"type": "Account"}, "Id": acc_id, "Rating": "Hot"}
for acc_id in os.environ["ACCOUNT_IDS"].split(",")[:200]
]
resp = requests.patch(
f"{instance_url}/services/data/v60.0/composite/sobjects",
headers={"Authorization": f"Bearer {token}"},
json={"allOrNone": False, "records": records},
timeout=60,
)
resp.raise_for_status()
failed = [r for r in resp.json() if not r["success"]]
print(f"Updated {len(records) - len(failed)} records, {len(failed)} failed")Set ACCOUNT_IDS to a comma-separated list of Account IDs before you run it. With allOrNone set to False, one bad record does not roll back the others, so always check the per-record results.
Use Bulk API for large volumes
For tens of thousands of records or more, use Bulk API 2.0. You submit a job and upload the data as CSV. Salesforce processes it asynchronously. Bulk API requests have their own allocation of batches per 24 hours, so they do not drain the same budget as REST calls in the same way. Check the current limits for your edition before you rely on this.
Cache stable data
Reference data such as picklist values, record type IDs, and object metadata changes rarely. Store it in memory or a local cache with an expiry time instead of fetching it on every run. A cache that lives for an hour can remove thousands of calls a day.
Replace polling with events
A job that queries "what changed?" every minute makes 1,440 calls a day, even when nothing changes. Instead, subscribe to Change Data Capture or Platform Events through the Pub/Sub API. Salesforce pushes a message when a record changes, and your integration makes calls only when it has work to do. Event delivery has its own allocations, so check those too.
Smaller savings
- Request only the fields you need in each SOQL query, and filter on the server instead of downloading everything.
- Use a single SOQL query with relationship fields in place of several queries on related objects.
- Use
queryMorepagination by followingnextRecordsUrl, and set sensible page sizes, rather than re-running the query. - Deduplicate requests in your own code so that the same record is not fetched twice in one run.
- Use conditional requests with
If-Modified-Sinceon resources that support it, so unchanged data returns a short response.
Confirm the result
After a change, compare the DailyApiRequests value from the Limits resource over several days. Look at the ApiTotalUsage logs again to confirm that the targeted client's share dropped.
Exercise
An integration polls Salesforce every 30 seconds to find changed Contacts, then updates each changed Contact with a separate PATCH request. About how many polling calls does it make per day, and which two changes would reduce total calls the most?
Show answer
Polling alone makes 2 calls per minute, which is 2,880 calls per day. Replacing the polling with Change Data Capture removes nearly all of them, and replacing the per-record PATCH requests with sObject Collections (up to 200 records per call) removes most of the update calls.
Exercise
You set allOrNone to False in a collections request. What must your code do after the response arrives?
Show answer
It must check the success flag of each record result, because failures in one record do not roll back or raise an error for the whole request. Failed records then need to be logged or retried.