Sub topic 8
Monitoring job progress
This chapter assumes you can already create an ingest job, upload CSV data, and set the state to UploadComplete. You also need a valid access token and the $INSTANCE_URL, $ACCESS_TOKEN and $JOB_ID values from earlier chapters. Here you learn how to ask Salesforce what a job is doing, how to read the answer, and how to write a polling loop that behaves well.
Why you have to poll
Bulk API 2.0 is asynchronous. When you send UploadComplete, Salesforce queues the job and returns immediately. It does not notify you when the job finishes. The only way to learn the outcome is to call the job info endpoint and read the state field.
Do not treat the PATCH response as proof that your data loaded. It only shows that the state change was accepted.
The job info request
Send a GET to the job's URL:
curl "$INSTANCE_URL/services/data/v62.0/jobs/ingest/$JOB_ID" \
-H "Authorization: Bearer $ACCESS_TOKEN"A response for a job that is partway through looks like this (trimmed):
{
"id": "750xx0000000001AAA",
"operation": "insert",
"object": "Contact",
"state": "InProgress",
"contentType": "CSV",
"apiVersion": 62.0,
"numberRecordsProcessed": 18000,
"numberRecordsFailed": 40,
"retries": 0,
"totalProcessingTime": 4210,
"apiActiveProcessingTime": 3980,
"apexProcessingTime": 120
}The fields you will use most:
| Field | Meaning |
|---|---|
| `state` | Where the job is in its lifecycle. |
| `numberRecordsProcessed` | Records Salesforce has attempted so far. This count includes records that failed. |
| `numberRecordsFailed` | Records that were attempted and rejected. |
| `retries` | How many times Salesforce retried parts of the job internally, for example after a lock error. |
| `totalProcessingTime` | Total time spent processing, in milliseconds. |
| `apexProcessingTime` | Time spent in triggers and other Apex code, in milliseconds. |
| `errorMessage` | Present when the job as a whole failed. |
Successful records are the processed count minus the failed count. Salesforce does not report a separate success counter in this response.
The states
An ingest job moves through a small set of states. Three of them are terminal, which means the job never leaves them.
| State | Meaning | Terminal? |
|---|---|---|
| `Open` | The job exists and accepts uploaded data. | No |
| `UploadComplete` | You closed the upload. The job is queued. | No |
| `InProgress` | Salesforce is processing records. | No |
| `JobComplete` | Processing finished. Individual records may still have failed. | Yes |
| `Failed` | The job could not be processed. | Yes |
| `Aborted` | You (or an admin) aborted the job. | Yes |
Bulk query jobs use the same names except that they have no Open state. They start at UploadComplete, because there is no upload step.
JobComplete does not mean success
This is the most common misreading. JobComplete says that Salesforce finished working through every record. It says nothing about how many succeeded. A job can reach JobComplete with every record failed, for instance when a required field is missing from the whole file.
After you see JobComplete, always compare numberRecordsFailed with zero. If it is above zero, fetch the failed results, which the next chapter covers.
Failed means the job itself broke
Failed is different. It means Salesforce could not process the job, and errorMessage usually says why. Typical causes are an unreadable file or an internal problem. Some records may have been processed before the failure, so check numberRecordsProcessed and the successful results before you resubmit anything. Otherwise you risk loading duplicates.
Writing a polling loop
A good loop does four things:
- It stops on any terminal state, not only
JobComplete. - It waits between requests, and the wait grows when the job is slow.
- It has an overall deadline, so a stuck job cannot hang your script.
- It reports progress so you can see that the job is moving.
Each poll counts against your org's API request allocation. Polling every second for a job that takes an hour wastes thousands of requests. Start with a short wait and back off to a cap.
import os
import time
import requests
TERMINAL_STATES = {"JobComplete", "Failed", "Aborted"}
def wait_for_job(base, job_id, headers, timeout=3600, first_wait=5, max_wait=60):
"""Poll an ingest job until it reaches a terminal state.
Returns the final job info dict. Raises TimeoutError if the
deadline passes first.
"""
deadline = time.monotonic() + timeout
wait = first_wait
while True:
resp = requests.get(f"{base}/{job_id}", headers=headers, timeout=30)
resp.raise_for_status()
info = resp.json()
print(
f"{info['state']}: processed={info.get('numberRecordsProcessed')} "
f"failed={info.get('numberRecordsFailed')}"
)
if info["state"] in TERMINAL_STATES:
return info
if time.monotonic() + wait > deadline:
raise TimeoutError(f"Job {job_id} still {info['state']} after {timeout}s")
time.sleep(wait)
wait = min(wait * 2, max_wait)
if __name__ == "__main__":
instance = os.environ["SF_INSTANCE_URL"]
token = os.environ["SF_ACCESS_TOKEN"]
job_id = os.environ["SF_JOB_ID"]
base = f"{instance}/services/data/v62.0/jobs/ingest"
headers = {"Authorization": f"Bearer {token}"}
info = wait_for_job(base, job_id, headers)
if info["state"] == "Failed":
print("Job failed:", info.get("errorMessage"))
elif info.get("numberRecordsFailed"):
print("Finished with failed records. Fetch failedResults next.")
else:
print("All records succeeded.")Two details matter here. The timeout=30 argument on each request stops one slow response from freezing the loop. The time.monotonic() clock is used for the deadline because it is not affected by system clock changes.
What to do when polling errors out
A single failed poll does not mean the job failed. The job runs on Salesforce's servers whether or not your script is connected.
- A
401means your access token expired. Refresh the token and keep polling the same job. Do not create a new one. - A
5xxor a network timeout is usually temporary. Retry the poll after a pause. - A
404means the job ID is wrong or the job was deleted.
If your script crashes, you lose nothing. Restart it with the saved job ID and it picks up where the job is now. For this reason, write the job ID to a log or file as soon as you create the job.
Listing and finding jobs
If you lose a job ID, list the org's ingest jobs:
curl "$INSTANCE_URL/services/data/v62.0/jobs/ingest" \
-H "Authorization: Bearer $ACCESS_TOKEN"The response has a records array of job info objects, a done flag, and a nextRecordsUrl when more jobs remain. Pass that URL to fetch the next page. The Setup page "Bulk Data Load Jobs" in Salesforce shows the same information in a browser, which helps when you are checking a job someone else started.
Aborting a job
You can stop a job that is Open, UploadComplete or InProgress with a state change:
curl -X PATCH "$INSTANCE_URL/services/data/v62.0/jobs/ingest/$JOB_ID" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"state":"Aborted"}'Aborting does not roll back records that were already processed. Those records stay in the org. Abort a running job only after you have thought about what to do with the partial load. Deleting a job with DELETE on the same URL works only once the job is JobComplete or Aborted, and it removes the job and its results, not the loaded records.
Common mistakes
- Waiting only for
JobComplete. AFailedorAbortedjob makes the loop run forever. Test against the full set of terminal states. - Polling too fast. Fast polling burns API requests and adds nothing, because progress is reported only as batches finish.
- Reading a fixed state once.
UploadCompletecan last a while if the org is busy. A job that has not reachedInProgressafter a minute is normal. - Assuming zero failures. Check
numberRecordsFailedevery time. - Resubmitting after
Failedwithout checking. Look at the results first to avoid duplicate records.
Exercise
Your script polls an insert job and sees state JobComplete, numberRecordsProcessed 50000 and numberRecordsFailed 1200. Did the load succeed? What do you do next, and why should the polling loop have stopped on Failed and Aborted as well?
Show answer
The job finished, but it only partly succeeded: about 48,800 records loaded and 1,200 were rejected. JobComplete means processing ended, not that every record was accepted. Next, download the failed results, fix the cause of each error, and resubmit only those rows in a new job. The loop must stop on Failed and Aborted because both are terminal states. A job in either state never reaches JobComplete, so a loop that waits only for JobComplete would run forever.