Bulk api patterns

From PranavNagrecha/AwesomeSalesforceSkills · View interactive version

Bulk api patterns is an AI agent skill from the GitHub repository PranavNagrecha/AwesomeSalesforceSkills. Use when implementing Bulk API 2.0 REST calls, choosing between Bulk API 2.0 and legacy Bulk API v1, handling CSV format requirements for bulk ingest, paginating query job results with locators, or constructing multipart job requests. Triggers: bulk api 2.0 endpoint, ingest job REST call, query job

How to use this skill

Skill file

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:


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:

  1. Open — Job created via POST /jobs/ingest/. Accepts CSV data uploads.
  2. 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.
  3. InProgress — Salesforce auto-creates internal batches (one per 10,000 records) and processes them asynchronously.
  4. JobComplete — All internal batches have been attempted. Individual records may still have failed — this state means processing is done, not that all records succeeded.
  5. 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.
  6. 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):

CSV Format Requirements

Bulk API 2.0 ingest jobs accept CSV data only. The format must conform to these requirements:

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:

  1. GET .../jobs/query/{jobId}/results — returns the first set of results and a Sforce-Locator response header.
  2. If Sforce-Locator is not null, there are more pages. Use the locator value in the next request: GET .../results?locator={locatorValue}.
  3. Repeat until Sforce-Locator is null.
  4. The optional maxRecords parameter 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

  1. 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.
  2. Transform the CSV: header names equal API names, #N/A wherever a field must be cleared, values trimmed, dateTimes in yyyy-MM-ddTHH:mm:ss.SSSZ.
  3. Implement the call sequence from Pattern 1 (or Pattern 2 for 100,000 characters or less), branching on the state returned at creation; for exports, Pattern 3 with a string comparison against null.
  4. Run python3 skills/data/bulk-api-patterns/scripts/check_bulk_api_patterns.py --manifest-dir <integration source> and fix every ERROR.
  5. Run the job against a sandbox with a few hundred rows, then reconcile with the script in references/reconciliation-script.md before the full run.
  6. 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:


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

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.