Sub topic 7
Batch sync: moving large volumes with Bulk API 2.0
This chapter assumes you know the Salesforce data model, REST and JSON basics, HTTP methods and status codes, and the idea of an external ID field. It also assumes you have read the earlier chapters on synchronous and asynchronous trade-offs and on Named Credentials. Here you will learn how batch sync works, how to design a Bulk API 2.0 upsert job, and which failures to plan for.
What batch sync is
Batch sync moves a large set of records between systems in one operation, on a schedule or when a volume threshold is reached. Examples include a nightly load of 2 million product prices from an ERP, an initial migration of historical orders, and a weekly extract of Accounts to a data warehouse.
Compared with the other two patterns:
| Aspect | Request-reply | Fire-and-forget | Batch sync |
|---|---|---|---|
| Timing | Caller waits | Publisher continues immediately | Job runs in the background, caller polls |
| Unit of work | One record or a few | One event | Thousands to millions of records |
| Coupling | Tight, both systems must be up | Loose, through the event bus | Loose, through a job object |
| Failure behavior | Immediate error to the caller | Subscriber fails separately | Per-record failures reported after the job |
Batch sync is the right choice when throughput matters more than latency. It is the wrong choice when a user is waiting for an answer.
Why Bulk API 2.0
The REST API handles records one request at a time, or up to 200 records per composite or collection call. Loading a million records that way costs thousands of API calls and a lot of time. Bulk API 2.0 accepts a whole CSV file in one upload. Salesforce splits the file into internal batches, processes them in parallel, and reports the results as downloadable files.
Bulk API 2.0 differs from the older Bulk API 1.0 in ways that simplify your client:
- You do not create or manage batches. You upload one CSV and Salesforce divides it for you.
- A job has a small set of states, and you drive it with a single state change.
- Results come back as three files per ingest job: successful, failed, and unprocessed records.
- It supports CSV only. Bulk API 1.0 also supports XML and JSON.
Bulk API 2.0 also supports query jobs for extracting large result sets. This chapter focuses on ingest, which is the direction that needs the most design care.
The ingest job lifecycle
An ingest job moves through a fixed sequence of states.
The client performs these steps:
- Create the job with a POST to
/jobs/ingest. The job starts in theOpenstate. - Upload CSV data with a PUT to the job's
batchesendpoint. - Set the state to
UploadCompletewith a PATCH. This tells Salesforce the data is final. - Poll the job until it reaches
JobComplete,Failed, orAborted. - Download the successful, failed, and unprocessed result files.
Step 1: Create an upsert job
The job definition names the object, the operation, and for upserts, the external ID field.
POST /services/data/v60.0/jobs/ingest
Content-Type: application/json
Authorization: Bearer <access_token>
{
"object": "Account",
"externalIdFieldName": "External_Id__c",
"contentType": "CSV",
"operation": "upsert",
"lineEnding": "LF"
}The response includes a job id and a contentUrl of the form services/data/v60.0/jobs/ingest/{jobId}/batches. The supported operations are insert, update, upsert, delete, and hardDelete. The lineEnding value must match the file. If you generate a CSV on Windows and declare LF, the parse will fail or produce bad values.
Step 2: Upload the CSV
The CSV header row holds field API names, and each following row is one record. Include the external ID column, because the job uses it to decide between insert and update.
PUT /services/data/v60.0/jobs/ingest/750xx0000000001AAA/batches
Content-Type: text/csv
Authorization: Bearer <access_token>
External_Id__c,Name,Industry
ERP-10042,Acme Corporation,Manufacturing
ERP-10043,Globex Ltd,Energy
ERP-10044,Initech,TechnologyA successful upload returns 201 Created. Keep each job's data within the documented size limit, which is currently 150 MB of base64-encoded content per upload. Because encoding inflates data by about a third, plan on roughly 100 MB of raw CSV per job and split larger files across multiple jobs. Check the current limit in the Salesforce documentation before you size your files, since limits change between releases.
Step 3: Close the upload
PATCH /services/data/v60.0/jobs/ingest/750xx0000000001AAA
Content-Type: application/json
Authorization: Bearer <access_token>
{ "state": "UploadComplete" }Until you send this, the job stays Open and does nothing. Forgetting it is a common bug. Salesforce deletes jobs that stay open for too long, so a script that crashes between the upload and this call leaves no useful state behind.
Step 4 and 5: Poll and collect results
Poll with GET /jobs/ingest/{jobId} and read the state, numberRecordsProcessed, and numberRecordsFailed fields. Use a growing interval, for example 5 seconds, then 10, then 30, and cap it. Polling every second wastes API calls and adds no speed.
When the state is JobComplete, fetch the result files:
| Endpoint suffix | Contents |
|---|---|
| `/successfulResults` | Records that saved, with `sf__Id` and `sf__Created` columns |
| `/failedResults` | Records that failed, with an `sf__Error` column |
| `/unprocessedrecords` | Records Salesforce never attempted, for example after an abort |
JobComplete does not mean every record succeeded. A job can finish with half its rows in failedResults. Your client must read the failure file every time and treat a nonzero numberRecordsFailed as a result that needs handling.
Idempotent loads with an external ID
The upsert operation is what makes a batch load safe to repeat. For each row, Salesforce looks for an existing record whose external ID field matches. If it finds one, it updates it. If not, it inserts a new record.
The same idea applies to the REST API for small corrections:
PATCH /services/data/v60.0/sobjects/Account/External_Id__c/ERP-10042
Content-Type: application/json
Authorization: Bearer <access_token>
{
"Name": "Acme Corporation",
"Industry": "Manufacturing"
}Running this request twice leaves one Account, not two. This property lets you retry a job after a timeout without first working out which rows landed.
The external ID field needs care:
- Mark it as External ID and Unique. Without uniqueness, two records can share a value, and an upsert that matches several records fails for those rows.
- Make it case-sensitive if the source system treats
abcandABCas different keys. Otherwise they collide. - Do not leave it blank in the file. Rows with an empty key are inserted as new records, which creates duplicates on every rerun.
- Duplicate keys inside the same file are a trap. Two rows with the same new key in one job can both try to insert, and one fails or overwrites the other depending on timing. Deduplicate before upload.
Parallel processing and record locks
Salesforce processes the internal batches of a job in parallel. That speed has a cost. Two batches that update records sharing a parent can compete for the same lock, and you see UNABLE_TO_LOCK_ROW errors in the failed results. Common causes are:
- Many child records (Contacts, Opportunities) for the same parent Account in one file.
- Triggers, flows, or roll-up summary fields that update a shared record.
- Two concurrent jobs touching the same records.
Mitigate lock contention by sorting the CSV so children of the same parent are adjacent. That keeps them in the same internal batch. Also avoid running overlapping jobs against the same object, and review automation that fires on each row. Rows that fail with lock errors are safe to resubmit, because the upsert is idempotent.
Automation also affects speed. Each row runs through triggers, validation rules, and flows, just as it would from the UI. Loading 5 million rows into an object with heavy automation can be slow, and it can hit governor limits inside your own trigger code. Write triggers to handle bulk input, and consider a bypass flag, such as a custom permission, for approved data migrations.
A client that handles the whole lifecycle
The following Apex-free Python script runs the full sequence. It uses the requests library and assumes you already hold an access token and an instance URL, for example from an OAuth flow for a connected app.
import time
import requests
INSTANCE = "https://example.my.salesforce.com"
TOKEN = "<access_token>"
API = f"{INSTANCE}/services/data/v60.0"
HEADERS = {"Authorization": f"Bearer {TOKEN}"}
def run_upsert(csv_path):
job = requests.post(
f"{API}/jobs/ingest",
headers={**HEADERS, "Content-Type": "application/json"},
json={
"object": "Account",
"externalIdFieldName": "External_Id__c",
"contentType": "CSV",
"operation": "upsert",
"lineEnding": "LF",
},
timeout=30,
)
job.raise_for_status()
job_id = job.json()["id"]
with open(csv_path, "rb") as f:
up = requests.put(
f"{API}/jobs/ingest/{job_id}/batches",
headers={**HEADERS, "Content-Type": "text/csv"},
data=f,
timeout=300,
)
up.raise_for_status()
requests.patch(
f"{API}/jobs/ingest/{job_id}",
headers={**HEADERS, "Content-Type": "application/json"},
json={"state": "UploadComplete"},
timeout=30,
).raise_for_status()
delay = 5
while True:
info = requests.get(
f"{API}/jobs/ingest/{job_id}", headers=HEADERS, timeout=30
).json()
if info["state"] in ("JobComplete", "Failed", "Aborted"):
break
time.sleep(delay)
delay = min(delay * 2, 60)
failed = requests.get(
f"{API}/jobs/ingest/{job_id}/failedResults",
headers=HEADERS,
timeout=60,
).text
return info, failed
if __name__ == "__main__":
info, failed = run_upsert("accounts.csv")
print(info["state"], info.get("numberRecordsFailed"))
print(failed)In production, replace the hard-coded token with a refreshed one, and use the integration platform's secret store. Inbound calls to Salesforce use an OAuth flow tied to a connected app, such as JWT bearer for server-to-server work. Named Credentials cover the outbound direction, which matters if Apex starts or monitors the job.
Failure modes and how to handle them
| Failure | Symptom | Response |
|---|---|---|
| Row-level validation error | Row in `failedResults` with an `sf__Error` message | Fix the data, then resubmit only the failed rows |
| Lock contention | `UNABLE_TO_LOCK_ROW` in failed results | Resubmit those rows, and sort or serialize future loads |
| Job-level failure | State `Failed` | Read `errorMessage` on the job, fix the cause, resubmit the whole job |
| Client crashes mid-run | Job left `Open` or `InProgress` | Store the job ID, then resume polling or abort the job |
| Daily limit reached | HTTP 403 with `REQUEST_LIMIT_EXCEEDED` | Wait for the limit window, and reduce the number of jobs |
| Token expired | HTTP 401 | Refresh the token and retry the call |
Persist the job ID as soon as you create the job. If your process restarts, it can find the job again instead of creating a duplicate.
A reliable batch client follows these rules:
- Make every load an upsert on a stable external ID, so a rerun is harmless.
- Record the job ID, input file name, and checksum in a log table.
- Always download
failedResultsand route failures to a person or a retry queue. - Resubmit only failed rows, and cap the number of retries.
- Keep job sizes moderate. Many medium jobs are easier to retry than one huge job.
Limits that affect batch sync
Bulk API 2.0 has its own limits, separate from per-transaction governor limits. Salesforce enforces a daily cap on the number of records processed through Bulk API 2.0 and a cap on the number of ingest jobs. The exact values depend on your edition and change between releases, so read them from the Limits resource instead of hard-coding them. You can query /services/data/v60.0/limits for the current remaining allowance before you start a large run.
Data size is another limit. A job accepts a bounded amount of data per upload, and fields have their own maximum lengths. A row with text longer than its field fails alone and does not stop the job.
When to choose batch sync
Choose Bulk API 2.0 when:
- The volume is large, from tens of thousands of records to millions.
- Nobody needs the result within seconds.
- The data moves on a schedule, or as a one-time load.
- Partial success is acceptable, and failed rows can be fixed and replayed.
Avoid it when a user is waiting, when each change must trigger an immediate reaction elsewhere, or when the volume is small. For a few hundred records, a REST collection call is simpler and returns an answer in the same response. For continuous change notifications, use platform events or Change Data Capture instead of running a bulk job every minute.
Exercise
A nightly job upserts 800,000 Accounts using Bulk API 2.0. The job state is JobComplete, but the next morning users find some Accounts missing. What do you check first, and why does the job state not settle the question?
Show answer
Check the failedResults file and the numberRecordsFailed value for the job. JobComplete only means Salesforce finished processing every row. It does not mean every row saved. Rows with validation errors, lock contention, or bad keys are written to failedResults. The client should always download that file and resubmit the fixable rows. Because the load is an upsert on an external ID, resubmitting is safe.
Exercise
Your CSV has some rows with an empty ExternalId_c column. What happens on each run, and how do you prevent it?
Show answer
Rows with a blank external ID cannot match an existing record, so each run inserts them as new records, which creates duplicates on every rerun. Prevent it by validating the file before upload: reject or fix rows with a blank key, and also remove duplicate keys inside the file. Marking the field Unique helps protect against duplicates among populated values.