Sub topic 3
The job model and job states
This chapter assumes you know the basics of REST calls, JSON, and how Salesforce objects and record IDs work. It also assumes you have an OAuth access token. Here you will learn what a Bulk API 2.0 job is, which states it moves through, and how to write code that reacts to each state correctly.
What a job is
In Bulk API 2.0, every operation is wrapped in a job. A job is a server-side record that stores:
- what you asked for (the object, the operation, the file format)
- the data you uploaded
- the current state
- counters and timings
- the results once processing ends
You never send records to an object endpoint directly. You create a job, attach data, tell Salesforce you are done, and read the results later. The calls are asynchronous. A call returns quickly, and the real work happens on Salesforce servers while you poll.
There are two kinds of job, each with its own endpoint:
| Kind | Endpoint | Operations | Data flow |
|---|---|---|---|
| Ingest | `/services/data/vXX.X/jobs/ingest` | `insert`, `update`, `upsert`, `delete`, `hardDelete` | You upload CSV, Salesforce writes records |
| Query | `/services/data/vXX.X/jobs/query` | `query`, `queryAll` | You send SOQL, Salesforce produces CSV |
Bulk API 2.0 has no batch resource that you manage. Older Bulk API 1.0 made you create batches inside a job. In 2.0, Salesforce splits the uploaded data into internal batches for you. The job is the only unit you handle.
Reading job information
A GET on a job's URL returns its current information. These are the fields you will use most:
| Field | Meaning |
|---|---|
| `id` | The job ID, used in every later URL |
| `state` | Where the job is in its life cycle |
| `object` | The Salesforce object, for example `Contact` |
| `operation` | `insert`, `update`, `upsert`, `delete`, `hardDelete`, `query` or `queryAll` |
| `numberRecordsProcessed` | Rows Salesforce has handled so far |
| `numberRecordsFailed` | Rows that produced an error |
| `retries` | How many times Salesforce retried internal batches |
| `totalProcessingTime` | Total processing time in milliseconds |
| `createdDate`, `systemModstamp` | When the job was created and last changed |
A response for a job that is still collecting data looks like this:
{
"id": "750xx0000000001AAA",
"operation": "insert",
"object": "Contact",
"createdById": "005xx000001X8UzAAK",
"createdDate": "2026-12-01T08:59:28.000+0000",
"systemModstamp": "2026-12-01T08:59:28.000+0000",
"state": "Open",
"concurrencyMode": "Parallel",
"contentType": "CSV",
"apiVersion": 62.0,
"jobType": "V2Ingest",
"lineEnding": "LF",
"columnDelimiter": "COMMA"
}The counters do not appear until processing has started. Code that reads numberRecordsProcessed should use a default value, such as info.get("numberRecordsProcessed", 0).
The states of an ingest job
An ingest job has six states.
| State | Meaning | What you can do |
|---|---|---|
| `Open` | The job exists and is waiting for data | Upload data, close it, or abort it |
| `UploadComplete` | You closed the upload and the job is queued | Wait, abort, or delete |
| `InProgress` | Salesforce is processing the data | Wait, abort |
| `JobComplete` | Processing finished | Read results, delete |
| `Failed` | The job could not be processed to the end | Read results, delete |
| `Aborted` | You or an administrator canceled the job | Delete |
Two of these states are easy to misread.
JobComplete means Salesforce is finished. It does not mean every record succeeded. A job with 10,000 rows and 300 errors still ends in JobComplete, with numberRecordsFailed set to 300. Always check the counters and the failed results.
Failed means the job as a whole hit a problem, such as an internal error or a processing failure. Records that Salesforce had already processed are not rolled back. After a Failed job, read the successful, failed and unprocessed results (covered in a later chapter) to learn what was written before deciding what to resubmit.
Salesforce also does not run the job as one database transaction. Each internal batch commits on its own. That is why a job can end up with some records written and some not.
Who moves the job
Only two transitions come from your code. Everything else is Salesforce's doing.
- You move
OpentoUploadCompletewith a PATCH. This is the signal that you have finished uploading. - You move a job to
Abortedwith a PATCH if you want to cancel it. - Salesforce moves the job from
UploadCompletetoInProgress, and then toJobCompleteorFailed.
Both PATCH requests use the same body shape, a JSON object with a state field. The values are case-sensitive, so UploadComplete works and uploadcomplete does not.
Why the Open state matters
A job in Open accepts uploaded data. Once you move it to UploadComplete, it accepts no more. If you try to upload to a job that is no longer Open, the request is rejected. An upload therefore cannot be extended later. If you realize you forgot rows, you create a new job.
An Open job also never starts on its own. If your script uploads the CSV and then crashes before sending the PATCH, nothing gets processed. Those jobs sit idle, count against your daily job limits, and are easy to forget. When your script handles errors, make it either close the job or abort it, and never leave it half-done.
The states of a query job
A bulk query job has no upload step, so it has no Open state. You send the SOQL in the creation request, and the job begins in UploadComplete. From there it follows the same path:
UploadCompleteInProgressJobComplete,FailedorAborted
A query job's results can only be fetched after JobComplete. A query job can also be aborted while it is still queued or running.
Polling and terminal states
A terminal state is one that never changes again. JobComplete, Failed and Aborted are terminal. Open, UploadComplete and InProgress are not.
The correct way to wait for a job is to poll its URL until the state is terminal. This script reads a job once and returns a plain decision. It uses the job ID and environment variables from the earlier setup.
import os
import requests
TERMINAL = {"JobComplete", "Failed", "Aborted"}
def job_status(kind: str, job_id: str) -> dict:
"""Return the job info for an ingest or query job."""
instance = os.environ["SF_INSTANCE_URL"]
token = os.environ["SF_ACCESS_TOKEN"]
url = f"{instance}/services/data/v62.0/jobs/{kind}/{job_id}"
resp = requests.get(url, headers={"Authorization": f"Bearer {token}"})
resp.raise_for_status()
return resp.json()
def next_step(info: dict) -> str:
state = info["state"]
failed = info.get("numberRecordsFailed", 0)
if state not in TERMINAL:
return "keep waiting"
if state == "Aborted":
return "job was canceled; nothing more will run"
if state == "Failed":
return "read all three result sets to see what was written"
if failed:
return f"read failedResults: {failed} rows need attention"
return "all rows succeeded"
if __name__ == "__main__":
info = job_status("ingest", os.environ["JOB_ID"])
print(info["state"], "->", next_step(info))Notice that the script treats JobComplete with failures as a distinct outcome. A script that stops at JobComplete and reports success will hide data problems.
Listing, aborting and deleting jobs
Besides reading a single job, you can work with jobs as a group:
- A GET on
/jobs/ingestor/jobs/querylists the jobs in the org. This is how you find jobs that a crashed script left behind. - A PATCH with
{"state":"Aborted"}cancels a job that has not finished. - A DELETE removes a job and its stored data. Salesforce only allows this once the job is in
UploadComplete,JobComplete,AbortedorFailed. AnOpenjob must be aborted first.
Finished jobs and their results do not stay on the server forever. Salesforce documents a retention period of seven days, so download results you need to keep before then.
Common mistakes
- Uploading to a job that has already moved past
Open. - Forgetting the closing PATCH, so the job stays idle.
- Treating
JobCompleteas "everything worked". - Assuming a
Failedjob wrote nothing, when processed records are kept. - Writing the state with the wrong case in a PATCH body.
- Trying to delete a job that is still
Open.
Exercise
Your script uploads a CSV to a new ingest job and then loses its network connection before it sends any PATCH. What state is the job in, what happens to the data, and what are two ways to resolve it?
Show answer
The job stays in Open. The uploaded data is stored but never processed, because only a PATCH to UploadComplete starts processing. You can resume by sending the PATCH with {"state":"UploadComplete"} if the upload finished correctly, or you can send {"state":"Aborted"} and then delete the job and start over with a new job.
Exercise
A job reaches JobComplete with numberRecordsProcessed 5000 and numberRecordsFailed 120. Is the job a success? What do you do next?
Show answer
The job finished, but it is not a full success. 120 rows failed. Fetch the failedResults, read the sf__Error column for the cause, fix the data, and submit those rows in a new job. The other 4880 rows were written and should not be sent again for an insert.
Exercise
Why does a bulk query job have no Open state?
Show answer
A query job has no data to upload. The SOQL is part of the creation request, so the job begins in UploadComplete and moves straight to InProgress and then a terminal state.