Bulk API Patterns
This skill activates when a practitioner needs to implement the actual REST API calls for Bulk API 2.0 ingest or query jobs, understand CSV format requirements, paginate through large query results, or choose between Bulk API 2.0 and legacy Bulk API v1. It covers the endpoint-level mechanics of bulk operations. It does not cover Data Loader UI steps or the strategic decision of when to use Bulk API vs. REST Composite — see related skills for those.
Before Starting
Gather this context before working on anything in this domain:
- Which API version are you targeting? Bulk API 2.0 is REST-based, uses OAuth 2.0 bearer tokens, and requires no WSDL. Legacy Bulk API v1 uses SOAP-based session tokens and requires WSDL knowledge. Prefer v2.0 for all new implementations unless a specific v1 capability is required (e.g., serial concurrency mode, XML/JSON content types, binary attachments, which the Bulk API guide limits to Attachment objects or Salesforce CRM Content).
- Most common wrong assumption. Developers assume
concurrencyMode: Parallelin Bulk API 2.0 is a meaningful configuration choice. It is not — Bulk API 2.0 only supports parallel mode, and theconcurrencyModefield is reserved for future use. Serial mode is exclusively a Bulk API v1 feature. - Key constraints in play. A Bulk API 2.0 ingest job accepts up to 150 MB of data after base64 encoding, so upload no more than about 100 MB of raw CSV per job and split larger files across jobs. Salesforce creates one internal batch per 10,000 records, up to 150,000,000 records per rolling 24 hours, and ingest batches count toward the 15,000-batch allocation shared with Bulk API v1. A multipart job creation request handles up to 100,000 characters of CSV and completes the upload for you.
Questions to Ask Before Configuring
| Ask | Why it matters | What a good answer adds |
|---|---|---|
| "How big is the CSV in MB, not rows?" | A job takes at most 150 MB after base64 encoding, about 100 MB of raw CSV (Gotcha 6) | A split into several jobs before the first upload |
| "On update, should a blank cell clear the field or leave it alone?" | Empty values are ignored on update; only #N/A sets null (Gotcha 3) | Source data transformed so the intent is explicit |
| "Was the file produced on Windows or by a tool that writes CRLF?" | The declared lineEnding must match the file (Gotcha 5) | A lineEnding value checked against the bytes |
| "Is any value padded with spaces, or quoted with spaces around the quotes?" | Field values aren't trimmed, and a space next to a double quote fails the row (Gotcha 7) | A trimming step in the export |
| "How does the client detect the last page of a query job?" | The end marker is the string null in the Sforce-Locator header (Gotcha 2) | A loop that compares strings and never guesses locators |
| "Does the pipeline create jobs both ways, multipart and standard?" | Multipart jobs are already upload-complete (Gotcha 4) | One code path that branches on the returned state |
| "Who reconciles the counts, and against which result sets?" | Unprocessed records exist only for failed or aborted jobs (Gotcha 8) | A reconciliation that reads the right resources for each terminal state |
A proper job design adds size planning, an explicit null policy, and a reconciliation step; "just uploading the file" produces jobs that silently skip blank fields, stall in Open, or lose rows nobody counted.
Core Concepts
Bulk API 2.0 vs. Legacy Bulk API v1
Bulk API 2.0 (released in API version 41.0 / Winter '18) is the current recommended API for all new bulk operations.
| Feature | Bulk API 2.0 | Bulk API v1 |
|---|---|---|
| Protocol | REST (no WSDL) | SOAP (requires WSDL) |
| Authentication | OAuth 2.0 bearer token | Session ID via SOAP login |
| Content types | CSV only | CSV, XML, JSON, binary attachments |
| Batching | Automatic (10,000 records/batch) | Manual (developer creates batches) |
| Concurrency modes | Parallel only (serial not available) | Parallel and Serial |
| Query PK chunking | Automatic | Manual invocation required |
| Result endpoints | Job-level: successfulResults, failedResults, unprocessedrecords | Per-batch result retrieval |
| Multipart create | Supported (single-call create + upload) | Not supported |
Use Bulk API v1 only when: (1) serial concurrency mode is required to prevent lock contention and Bulk API 2.0 batching cannot be reorganized to avoid it, or (2) the data format is XML/JSON or includes binary attachments (Attachment objects or Salesforce CRM Content, per the Bulk API guide L4948).
Ingest Job Lifecycle
Every Bulk API 2.0 ingest job follows a strict state machine:
- Open — Job created via
POST /jobs/ingest/. Accepts CSV data uploads. - UploadComplete — Caller sends
PATCH /jobs/ingest/{jobId}with{"state": "UploadComplete"}. This is mandatory — Salesforce will not begin processing without it. A multipart job creation request bypasses this step by transitioning automatically. - InProgress — Salesforce auto-creates internal batches (one per 10,000 records) and processes them asynchronously.
- JobComplete — All internal batches have been attempted. Individual records may still have failed — this state means processing is done, not that all records succeeded.
- Failed — Salesforce could not complete the job: a batch still failed after 20 retries (each batch has 5 minutes), or the daily record limit was exceeded mid-job. Remaining data isn't processed.
- Aborted — Job manually canceled by the creator or a user with the Manage Data Integrations permission.
After the job reaches a terminal state, retrieve results (available for 7 days):
GET .../successfulResults/— records written successfully, withsf__Idandsf__Createdcolumns.GET .../failedResults/— records that failed at the record level, with ansf__Errorcolumn.GET .../unprocessedrecords/— for failed or aborted jobs only: records that were never processed. The documented path is lowercase.
CSV Format Requirements
Bulk API 2.0 ingest jobs accept CSV data only. The format must conform to these requirements:
- Encoding: UTF-8.
- Line endings: Specified at job creation time using the
lineEndingfield. Values:LF(default, Unix/macOS) orCRLF(Windows/DOS). Mismatch between the declaredlineEndingand the actual file causes parse errors. - Column delimiter: Default is
COMMA. Alternatives:BACKQUOTE,CARET,PIPE,SEMICOLON,TAB. Declared at job creation viacolumnDelimiter. - First row: Column headers matching Salesforce field API names. Relationship fields use dot notation:
Account.Name,Owner.Email. - Null values: Empty values are ignored when you update records. To set a field to null, use
#N/A. - Whitespace: Field values aren't trimmed; a space before or after a delimiter is part of the value, and a space before or after a double quote fails the row.
- Date/time fields:
yyyy-MM-ddTHH:mm:ss.SSSZoryyyy-MM-ddTHH:mm:ss.SSS+/-HH:mm, for example2024-01-15T10:30:00.000Z. - Header row: up to 32,000 characters; headers must match field API names.
Query Job and Locator Pagination
Query jobs return results as paginated CSV. The result set is not available as a single download for large queries.
Pagination pattern:
GET .../jobs/query/{jobId}/results— returns the first set of results and aSforce-Locatorresponse header.- If
Sforce-Locatoris notnull, there are more pages. Use the locator value in the next request:GET .../results?locator={locatorValue}. - Repeat until
Sforce-Locatorisnull. - The optional
maxRecordsparameter caps each set; without it the server uses a default based on the service. Set it when large sets time out on the client.
As long as the job exists, a locator does not change and can be used to fetch the same set again. Use only values returned in the header; the guide says not to construct or guess them. Bulk API 2.0 query jobs also automatically apply PK chunking for large queries, splitting the query into sub-queries by primary key range.
Common Patterns
Pattern 1: Standard Ingest Job — Create, Upload, Signal, Poll, Retrieve
When to use: Any insert, update, upsert, delete, or hardDelete operation on >2,000 records using a pre-built CSV file.
How it works:
Step 1 — Create the job
POST /services/data/v66.0/jobs/ingest/
Authorization: Bearer {token}
Content-Type: application/json
{
"object": "Account",
"operation": "insert",
"contentType": "CSV",
"lineEnding": "LF"
}
Response: { "id": "{jobId}", "state": "Open", "contentUrl": "..." }
Step 2 — Upload CSV data (at most 150 MB base64 per job, about 100 MB raw)
PUT /services/data/v66.0/jobs/ingest/{jobId}/batches
Authorization: Bearer {token}
Content-Type: text/csv
Name,Industry,Phone
Acme Corp,Technology,415-555-0100
...
Step 3 — Signal upload complete (MANDATORY — job never starts without this)
PATCH /services/data/v66.0/jobs/ingest/{jobId}
Content-Type: application/json
{ "state": "UploadComplete" }
Step 4 — Poll until terminal state
GET /services/data/v66.0/jobs/ingest/{jobId}
(Poll every 15–30 seconds; stop when state is JobComplete, Failed, or Aborted)
Step 5 — Retrieve all three result endpoints
GET /services/data/v66.0/jobs/ingest/{jobId}/successfulResults/
GET /services/data/v66.0/jobs/ingest/{jobId}/failedResults/
GET /services/data/v66.0/jobs/ingest/{jobId}/unprocessedrecords/ (Failed or Aborted jobs)
Integrity check: count(successful) + count(failed) [+ count(unprocessed)] == total uploaded records
Why not synchronous REST: The limits guide calls any operation over 2,000 records a good candidate for Bulk API 2.0 and recommends bulkified synchronous calls (such as Composite) below that. A regular composite request carries at most 25 subrequests (composite graphs, 500).
Pattern 2: Multipart Job Creation (Small Datasets)
When to use: Datasets up to 100,000 characters of CSV where you want to create the job and upload data in a single HTTP call, and avoid the manual UploadComplete PATCH.
How it works:
POST /services/data/v67.0/jobs/ingest/
Content-Type: multipart/form-data; boundary="BOUNDARY"
Authorization: Bearer {token}
--BOUNDARY
Content-Disposition: form-data; name="job"
Content-Type: application/json; charset=UTF-8
{
"object": "Contact",
"operation": "upsert",
"externalIdFieldName": "Integration_Id__c",
"contentType": "CSV",
"lineEnding": "LF"
}
--BOUNDARY
Content-Disposition: form-data; name="content"
Content-Type: text/csv
FirstName,LastName,Integration_Id__c
Jane,Smith,EXT-001
...
--BOUNDARY--
A multipart job transitions directly to UploadComplete state on creation. No separate PATCH is required. Poll and retrieve results the same way as the standard pattern.
Pattern 3: Query Job with Locator Pagination
When to use: Extracting large record sets (>50,000 records, or any query that would time out synchronously).
How it works:
Step 1 — Create query job
POST /services/data/v66.0/jobs/query
{
"operation": "query",
"query": "SELECT Id, Name, Industry FROM Account WHERE CreatedDate > 2024-01-01T00:00:00Z"
}
Step 2 — Poll until JobComplete
GET /services/data/v66.0/jobs/query/{jobId}
Step 3 — Retrieve first page of results
GET /services/data/v66.0/jobs/query/{jobId}/results
Response headers include: Sforce-Locator: MTAwMDA
Step 4 — Retrieve subsequent pages while Sforce-Locator != "null"
GET /services/data/v66.0/jobs/query/{jobId}/results?locator=MTAwMDA
GET /services/data/v66.0/jobs/query/{jobId}/results?locator=MjAwMDAw
...
(Continue until Sforce-Locator header is the literal string "null")
Use maxRecords to cap the size of each set (the guide's example uses 50,000). A locator does not change while the job exists, so a saved locator resumes an interrupted download.
Pattern 4: Hard Delete
When to use: Permanently removing records without leaving them in the Recycle Bin — typically for compliance/data purging or when Recycle Bin bloat causes query degradation.
Requirements: The running user needs the "Bulk API Hard Delete" permission, which is disabled by default and must be enabled by an administrator; a Salesforce user license is required.
How it works: Use operation hardDelete instead of delete in the job creation body. All other steps in the standard ingest pattern are identical. Records bypassed from the Recycle Bin cannot be recovered via standard Recycle Bin restore — ensure data is verified before submitting a hardDelete job.
Decision Guidance
| Situation | Recommended Approach | Reason |
|---|---|---|
| New bulk implementation, any volume | Bulk API 2.0 | Simpler, no WSDL, auto-batching, unified results |
| Serial concurrency required | Bulk API v1 with concurrencyMode: Serial | v2.0 only supports parallel; serial is v1-only |
| Binary attachment fields (ContentVersion) | Bulk API v1 with ZIP content type | v2.0 supports CSV only |
| Dataset < 100,000 characters | Multipart job creation | Single HTTP call; auto-completes UploadComplete |
| Large extract (>50,000 records) | Query job with locator pagination | Auto PK chunking; stable paginated results |
| Permanent deletion, no Recycle Bin | hardDelete operation | delete soft-deletes; hardDelete removes permanently |
| Upsert with external ID | Bulk API 2.0 ingest, upsert operation | Handles insert + update in one pass; specify externalIdFieldName |
| XML/JSON data format required | Bulk API v1 | v2.0 accepts CSV only |
Recommended Workflow
- Record the operation, object, external ID field, file size in MB, line endings, delimiter, and null policy in
templates/bulk-api-patterns-template.md; split files over about 100 MB raw into separate jobs. - Transform the CSV: header names equal API names,
#N/Awherever a field must be cleared, values trimmed, dateTimes inyyyy-MM-ddTHH:mm:ss.SSSZ. - Implement the call sequence from Pattern 1 (or Pattern 2 for 100,000 characters or less), branching on the
statereturned at creation; for exports, Pattern 3 with a string comparison againstnull. - Run
python3 skills/data/bulk-api-patterns/scripts/check_bulk_api_patterns.py --manifest-dir <integration source>and fix every ERROR. - Run the job against a sandbox with a few hundred rows, then reconcile with the script in
references/reconciliation-script.mdbefore the full run. - Keep the source CSV until reconciliation passes; results are only retrievable for 7 days.
Review Checklist
Run through these before marking work in this area complete:
- [ ] API version confirmed — Bulk API 2.0 for new implementations, v1 only when serial mode or non-CSV format is required
- [ ]
lineEndingfield in job creation matches the actual line endings in the CSV file (LF vs CRLF) - [ ]
columnDelimiterdeclared if not using the default COMMA - [ ] Each job's data stays under 150 MB after base64 encoding (about 100 MB raw CSV); larger files are split across jobs
- [ ]
UploadCompletePATCH is sent (or multipart creation used) — job remains in Open state indefinitely without it - [ ] Poll loop handles all three terminal states:
JobComplete,Failed,Aborted - [ ]
successfulResultsandfailedResultsretrieved after every job, plusunprocessedrecordsfor Failed or Aborted jobs - [ ] Integrity check performed: record counts across the result sets sum to total uploaded
- [ ] For query jobs: locator pagination loop terminates when
Sforce-Locatorheader value is the literal string"null" - [ ]
hardDeletepermission verified on running user before submitting hardDelete jobs
Salesforce-Specific Gotchas
Full write-ups are in references/gotchas.md:
| # | Gotcha |
|---|---|
| 1 | concurrencyMode is for future use; Bulk API 2.0 is parallel only |
| 2 | The last-page marker is the string null |
| 3 | Empty cells are ignored on update; #N/A clears a field |
| 4 | Multipart jobs are already upload-complete |
| 5 | lineEnding must match the file |
| 6 | 150 MB is a per-job ceiling, not per request |
| 7 | Field values aren't trimmed |
| 8 | Unprocessed records exist only for failed or aborted jobs |
Output Artifacts
| Artifact | Description |
|---|---|
| Ingest job REST call sequence | Step-by-step HTTP calls for create, upload, signal, poll, and result retrieval |
| CSV format specification | Encoding, line ending, delimiter, null value, and header row requirements |
| Query job pagination pattern | Locator-based loop to exhaust all result pages |
| API version selection rationale | v2.0 vs v1 decision with justification for the chosen approach |
| Metadata XML | Not applicable: Bulk API jobs are runtime REST calls, not deployable metadata (standards/skill-authoring-style.md § 4) |
Related Skills
- data/bulk-api-and-large-data-loads — for strategic decisions on when to use Bulk API, record volume thresholds, concurrency mode selection, and failed-record retry strategy
- data/data-migration-planning — for end-to-end migration planning including pre-load validation and post-load verification
- data/soql-query-optimization — for optimizing the SOQL query used in a query job to minimize processing time
- admin/data-import-and-management — for Data Loader UI steps and declarative import tooling