Sub topic 7
Bulk API 2.0 for large data volumes
This chapter assumes you can authenticate with OAuth 2.0 and obtain an access token, that you know basic SOQL, and that you have called the REST API with curl. It covers Bulk API 2.0 ingest and query jobs, how to read job results, and the errors people hit most often.
Why a separate bulk API exists
The REST API handles one request at a time and returns an answer right away. That works well for a few records. It becomes costly when you load 2 million contacts: each call uses API quota, and your client has to manage retries and pacing.
Bulk API 2.0 is an asynchronous API for large data sets. You submit a job, Salesforce processes it in the background, and you poll for the outcome. You send one CSV file and Salesforce splits it into internal batches for you. Bulk API 2.0 differs from the older Bulk API 1.0 in that you do not create or size batches yourself.
Typical uses:
- Initial data loads and migrations.
- Nightly syncs from a data warehouse.
- Mass updates and deletes.
- Exporting large query results.
Avoid it when a user is waiting for a response. A job can take seconds or hours, and you cannot predict which.
The job model
Every Bulk API 2.0 operation is a job. A job has an object, an operation, and a state. The two job families are ingest (write data) and query (read data).
| Family | Operations | Input | Output |
|---|---|---|---|
| Ingest | `insert`, `update`, `upsert`, `delete`, `hardDelete` | CSV upload | Successful, failed, and unprocessed result files |
| Query | `query`, `queryAll` | SOQL string | CSV result pages |
upsert needs an externalIdFieldName on the job. hardDelete skips the Recycle Bin and requires a special permission, so treat it as irreversible.
Ingest job lifecycle
An ingest job moves through a small set of states.
The three calls below create the job, upload data, and close the upload. Replace MyDomain with your My Domain name and use an API version your org supports.
# 1. Create the ingest job
curl -X POST "https://MyDomain.my.salesforce.com/services/data/v60.0/jobs/ingest" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"object": "Contact", "operation": "insert", "contentType": "CSV", "lineEnding": "LF"}'
# 2. Upload the CSV data (JOB_ID comes from the response above)
curl -X PUT "https://MyDomain.my.salesforce.com/services/data/v60.0/jobs/ingest/$JOB_ID/batches" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: text/csv" \
--data-binary @contacts.csv
# 3. Tell Salesforce the upload is finished so processing starts
curl -X PATCH "https://MyDomain.my.salesforce.com/services/data/v60.0/jobs/ingest/$JOB_ID" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"state": "UploadComplete"}'The first response includes the job id and "state": "Open". Nothing is processed until step 3. A common mistake is to upload the data and forget the UploadComplete patch, which leaves the job open until Salesforce deletes it.
Preparing the CSV
The first row is a header of field API names. Column names must match fields on the target object, for example:
FirstName,LastName,Email,AccountId
Ada,Lovelace,[email protected],001000000000001AAA
Grace,Hopper,[email protected],001000000000001AAAPoints that cause failures:
- The
lineEndingvalue in the job (LForCRLF) must match the file. - Upload size is limited per job (about 150 MB of base64-encoded data per upload), so split very large files into several jobs.
- Empty cells are ignored on update. To clear a field, send
#N/A. - Relationship columns use the form
Account.ExternalId__cwhen you reference a parent by external ID.
Upload data with PUT once per job. Bulk API 2.0 does not let you add more data after the upload is marked complete.
Monitoring the job
Poll the job until it reaches a final state:
curl "https://MyDomain.my.salesforce.com/services/data/v60.0/jobs/ingest/$JOB_ID" \
-H "Authorization: Bearer $ACCESS_TOKEN"The response includes state, numberRecordsProcessed, and numberRecordsFailed. Poll every 10 to 30 seconds at first and back off for long jobs. Tight polling loops waste API calls.
Reading results
A JobComplete state does not mean every record succeeded. It means processing finished. Fetch three result files:
BASE="https://MyDomain.my.salesforce.com/services/data/v60.0/jobs/ingest/$JOB_ID"
curl "$BASE/successfulResults/" -H "Authorization: Bearer $ACCESS_TOKEN" -o success.csv
curl "$BASE/failedResults/" -H "Authorization: Bearer $ACCESS_TOKEN" -o failed.csv
curl "$BASE/unprocessedrecords/" -H "Authorization: Bearer $ACCESS_TOKEN" -o unprocessed.csv| File | Contents | What to do |
|---|---|---|
| `successfulResults` | Created or updated records with `sf__Id` and `sf__Created` | Store new IDs for later joins |
| `failedResults` | Original row plus `sf__Error` | Fix data and resubmit only these rows |
| `unprocessedrecords` | Rows never attempted, such as after a job failure | Resubmit in a new job |
The failed file keeps your original columns, so a corrected version is easy to build. Remove the sf__Id and sf__Error columns before resubmitting.
Query jobs
For exports, post a SOQL statement and download the result in pages.
curl -X POST "https://MyDomain.my.salesforce.com/services/data/v60.0/jobs/query" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"operation": "query", "query": "SELECT Id, Name FROM Account"}'Poll GET /jobs/query/$JOB_ID until state is JobComplete. Then read GET /jobs/query/$JOB_ID/results. Large results are split across pages. The response headers include Sforce-Locator. If its value is not null, request the next page with ?locator=VALUE. The header Sforce-NumberOfRecords reports how many records the page holds.
Bulk query supports most SOQL but not everything. Relationship queries that traverse child-to-parent work in many cases, but GROUP BY, OFFSET, and TYPEOF are not supported. Check the current documentation for your API version.
Processing behavior and limits
Understanding what happens inside a job helps you diagnose slow or failed loads.
- Salesforce splits the upload into chunks and processes them in parallel. This makes record order within the job unreliable, and it can cause row locks.
- Each chunk runs as an independent transaction, so a failure in one chunk does not roll back the others. Partial success is normal.
- Triggers, flows, validation rules, and duplicate rules all run during ingest. A trigger that calls out or performs heavy queries slows the whole job.
- Bulk API 2.0 usage counts against a daily allocation of records processed, and not against the REST request quota in the same way. Check your org's limits in Setup or with the
/limitsREST resource.
Limits change between releases. Read the current Salesforce limits documentation before you design a pipeline around specific numbers.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `UNABLE_TO_LOCK_ROW` in failed results | Parallel chunks update records sharing a parent, such as many contacts of one account | Sort the CSV by parent ID, split into smaller jobs, or run related loads one after another |
| Job stays `Open` | `UploadComplete` was never sent | Send the `PATCH` |
| `InvalidBatch` or column errors | Header does not match field API names | Correct the header row |
| `REQUIRED_FIELD_MISSING` | Required field blank in some rows | Fix those rows from `failedResults` |
| `Failed` state with unprocessed rows | System error or size problem | Read `errorMessage` on the job, resubmit unprocessed rows |
| `INVALID_SESSION_ID` mid-job | Token expired while polling | Refresh the token and keep the same job ID |
Disabling automation during a data migration can help, but only do so with a clear plan to re-enable it, and consider a bypass flag that triggers and flows check, rather than turning them off org-wide.
Choosing Bulk API 2.0 over REST
A rule of thumb: when a load reaches thousands of records and nobody needs the answer immediately, use Bulk API 2.0. For hundreds of records or fewer, or when you need instant feedback, use REST, possibly with Composite requests. For continuous small changes, use event-driven integration instead of repeated bulk jobs.
Exercises
Exercise
A job you created shows state: Open an hour after you uploaded 500,000 rows, and numberRecordsProcessed is 0. What happened, and what is the fix?
Show answer
The upload was never marked complete. Bulk API 2.0 starts processing only after a PATCH to the job with {"state": "UploadComplete"}. Send that request.
Exercise
Your job ends as JobComplete but numberRecordsFailed is 4,200, mostly with UNABLE_TO_LOCK_ROW. Give two ways to reduce these errors and say how you would retry the failed rows.
Show answer
Sort the CSV so rows with the same parent record sit together, or split the load into smaller jobs run one after another, so parallel chunks stop competing for the same parent lock. To retry, download failedResults, remove the sf__Id and sf__Error columns, and submit the remainder as a new job.
Exercise
You must sync 50 changed Account records every few seconds, and also load 3 million historical Contacts once. Which API fits each task?
Show answer
Use REST (or an event-driven API such as Change Data Capture if the changes originate in Salesforce) for the small, frequent sync, since it responds immediately. Use a Bulk API 2.0 ingest job for the historical load because of the volume and because the result can arrive later.