Sub topic 10
Working within API limits and handling large objects
Small orgs export without trouble. Large orgs hit a different set of problems: query timeouts, exhausted API allocations, and files too big to move in one request. This chapter covers the limits that affect exports and the techniques that keep a backup running when an object holds millions of rows.
It assumes you can write basic SOQL, have run a Data Loader or Salesforce CLI export, and know how to authorize an org alias. Limit values change between releases, so confirm the numbers in your org before you rely on them.
The limits that matter for exports
Three kinds of limit affect a backup job.
- API request allocation. Each org gets a rolling 24-hour allowance of API calls. It depends on the edition and on how many user licenses you have. Every REST or SOAP call counts, and so does every page of a query result.
- Bulk API limits. Bulk API 2.0 query jobs have their own daily caps on job count and total result size. Bulk queries use far fewer calls per record than REST queries.
- Query execution limits. A synchronous query that runs for more than about two minutes times out. Queries that filter on non-indexed fields over large tables are the usual cause.
Check your current usage before you design a schedule:
sf limits api display --target-org my-prod-aliasLook at DailyApiRequests first. Newer API versions also report Bulk API 2.0 query counters. Compare Remaining with Max, and schedule exports at a time when other integrations are quiet.
Choosing a method by volume
The right API depends on how many records you need to read.
| Records in the object | Recommended approach | Why |
|---|---|---|
| Up to tens of thousands | `sf data query` or Data Loader with the standard API | Simple. Each page of results costs one API call. |
| Hundreds of thousands to millions | Bulk API 2.0 query job | Salesforce splits the work and returns large result files. |
| Tens of millions or more | Bulk API 2.0 with queries split by date or Id range | Each query stays selective and finishes inside the limits. |
| Files and attachments | REST download per record, or the Data Export Service | Bulk API 2.0 queries do not return blob content. |
The row thresholds are rules of thumb, not Salesforce limits. Row width, the number of fields, and org load all change where the cut-over belongs.
Keeping queries selective
A selective query uses an index to narrow the rows before it reads them. Standard indexed fields include Id, Name, OwnerId, CreatedDate, SystemModstamp, and lookup or master-detail fields. LastModifiedDate is often indexed too, but check your org. Filtering on an indexed field keeps the query fast. A filter on a custom text field without an index, or a leading wildcard such as LIKE '%abc', forces a full table scan. On a large object that scan can time out.
Two practical rules follow from this.
- For a full export, filter on
CreatedDateorIdranges, not on business fields. - For incremental exports, filter on
SystemModstamp. It changes whenever a record or its system fields change, so it catches more changes thanLastModifiedDate.
If an important custom field must be filtered and is not indexed, ask Salesforce Support about a custom index. For very large objects, ask about skinny tables too.
Slicing a large export
When one query over the whole object is too large, run several smaller queries over non-overlapping ranges and combine the results. Use half-open ranges (>= start, < end) so no record is read twice or skipped.
The script below exports Account one year at a time with the CLI's Bulk API 2.0 export command. It needs a recent Salesforce CLI. Run sf data export bulk --help to confirm the flags in your version.
#!/usr/bin/env bash
set -euo pipefail
ORG="my-prod-alias"
DEST="backup/accounts"
mkdir -p "$DEST"
for YEAR in $(seq 2018 2026); do
NEXT=$((YEAR + 1))
sf data export bulk \
--query "SELECT Id, Name, Industry, OwnerId, CreatedDate FROM Account WHERE CreatedDate >= ${YEAR}-01-01T00:00:00Z AND CreatedDate < ${NEXT}-01-01T00:00:00Z" \
--output-file "$DEST/Account_${YEAR}.csv" \
--result-format csv \
--wait 30 \
--target-org "$ORG"
doneIf one year holds most of your data, split that year by month. Slices that are too uneven defeat the purpose. After the run, add up the row counts of the slices and compare the total with SELECT COUNT() FROM Account, as described in the verification chapter.
Downloading large Bulk API 2.0 results
A Bulk API 2.0 query job can produce a result set too big for one response. You page through it with a locator. Each response carries a Sforce-Locator header. Pass its value to the next request, and stop when the header is null or missing.
#!/usr/bin/env bash
set -euo pipefail
# Requires INSTANCE_URL, ACCESS_TOKEN, and JOB_ID in the environment,
# and a job whose state is JobComplete.
LOCATOR=""
PART=0
while :; do
URL="$INSTANCE_URL/services/data/v60.0/jobs/query/$JOB_ID/results?maxRecords=500000"
if [ -n "$LOCATOR" ]; then
URL="$URL&locator=$LOCATOR"
fi
curl -sS -D headers.txt "$URL" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-o "part_${PART}.csv"
LOCATOR="$(grep -i '^Sforce-Locator:' headers.txt | awk '{print $2}' | tr -d '\r')"
PART=$((PART + 1))
if [ -z "$LOCATOR" ] || [ "$LOCATOR" = "null" ]; then
break
fi
done
# Each part starts with its own header row. Keep one header when merging.
head -n 1 part_0.csv > all.csv
for F in part_*.csv; do
tail -n +2 "$F" >> all.csv
doneResult files are kept for a limited time after the job completes, so download them promptly. The same restriction applies to Bulk API 2.0 queries in general. They cannot use GROUP BY, OFFSET, or parent-to-child subqueries. Export each child object with its own query.
Handling files and long text
Content that is stored as a blob needs special handling.
- Files live in
ContentVersion. Query the metadata (Id,Title,FileExtension,ContentSize,ContentDocumentId) in bulk, then download each body from/services/data/v60.0/sobjects/ContentVersion/<Id>/VersionData. Each download is one API call, so a million files is a million calls. Plan the allowance, or use the Data Export Service, which packages files in its zip archives. - Attachments are the older mechanism. Their bodies are exported the same way, through the
Bodyfield of each record. - Long text areas and rich text are exported as normal CSV fields. Check that your CSV reader handles embedded line breaks and quotes, or your row counts will look wrong.
Record the ContentSize total before you start. It tells you how much storage the backup needs and how long the download will take.
Retrying and resuming
Large jobs fail partway through, so build in recovery.
- Write each slice to its own file. A failed slice is rerun alone.
- Retry on
REQUEST_LIMIT_EXCEEDEDand on network errors with an increasing delay, such as 1, 2, then 4 minutes. - Log the slice boundaries, job Ids, and row counts. These logs are what let you prove completeness later.
Exercise
An Opportunity object has 40 million rows and a full-table query times out. Name two changes that make the export succeed, and state which field you would slice on.
Show answer
Run the export as a Bulk API 2.0 query job, and split it into non-overlapping CreatedDate ranges (for example one month each) so every query is selective and finishes within the limits. CreatedDate is indexed and never changes, so the ranges are stable. Use half-open ranges (>= start, < end) so no row is read twice or skipped. Then compare the sum of the slice counts with SELECT COUNT() FROM Opportunity.
Exercise
Why can a backup of one million files use up the daily API allocation even though the query for the file list is a single Bulk API job?
Show answer
Bulk API 2.0 queries cannot return blob content, so each file body must be downloaded from the VersionData endpoint, one REST call per file. A million files means about a million API calls, which can exceed the allocation. Use the Data Export Service for file content, or spread the downloads over several days.