Sub topic 11
Handling failures and resubmitting records
This chapter assumes you can already create, upload, close and monitor an ingest job, and that you know where the successful, failed and unprocessed result files come from. Here you decide what to do with them: classify each failure, build a clean resubmission file, and retry without creating duplicates or looping forever.
Three kinds of failure
Bulk API 2.0 failures happen at three levels, and each level needs a different response.
| Level | What you see | Typical cause | Response |
|---|---|---|---|
| Request | An HTTP 4xx or 5xx on create, upload or close | Expired token, bad JSON, wrong content type, malformed CSV header | Fix the request and repeat that call. No records were processed. |
| Job | Job state `Failed` or `Aborted` | Unreadable CSV, an unknown field in the header, an internal error, or a manual abort | Read `errorMessage` on the job. Fetch unprocessed records. |
| Record | Row appears in `failedResults` | Validation rule, missing required field, lock contention, bad lookup value | Classify the error. Fix the data or retry as is. |
A job in state JobComplete does not mean every record succeeded. It means Salesforce finished trying. Always compare numberRecordsFailed with zero before you treat a load as done.
Triage flow
The diagram shows the decision you make after a job reaches a terminal state.
Reading the failed rows
Each row in failedResults holds two added columns followed by the columns you uploaded.
sf__Idis the record ID if one exists. For a failed insert it is normally empty.sf__Erroris the failure reason. It begins with a status code, then a colon, then a message, for exampleREQUIRED_FIELD_MISSING:Required fields are missing: [LastName]:LastName --.
The status code is the part you classify on. Everything before the first colon is stable enough to match in code. The message text after it can change, so avoid matching on it.
Retryable and permanent errors
Retrying only helps when the cause is temporary. Retrying a validation failure wastes a job and gives the same result.
| Status code | Meaning | Action |
|---|---|---|
| `UNABLE_TO_LOCK_ROW` | Another transaction held a lock on the record or a related parent | Retry, ideally with less parallelism |
| `SERVER_UNAVAILABLE` | Transient platform problem | Retry after a delay |
| `REQUIRED_FIELD_MISSING` | A required field is blank | Fix data |
| `FIELD_CUSTOM_VALIDATION_EXCEPTION` | A validation rule rejected the row | Fix data or the rule |
| `INVALID_CROSS_REFERENCE_KEY` | A lookup ID points to nothing valid | Fix data, or load the parent first |
| `DUPLICATE_VALUE` | A unique or external ID value already exists | Switch to upsert, or fix data |
| `STRING_TOO_LONG` | A value exceeds the field length | Fix data |
Building the resubmission file
You cannot upload failedResults directly. The sf__Id and sf__Error columns are not fields on the object, so the job would fail on the header. Strip them, keep the original columns in their original order, and write the result as a new CSV.
The script below splits a failed-results file into a retry file and a review file. It uses the csv module so quoted commas and embedded line breaks survive the round trip.
import csv
RETRYABLE = {"UNABLE_TO_LOCK_ROW", "SERVER_UNAVAILABLE"}
def split_failures(failed_path, retry_path, review_path):
"""Split failedResults into a retry CSV and a review CSV.
Returns (retry_count, review_count).
"""
retry_count = review_count = 0
with open(failed_path, newline="", encoding="utf-8") as src:
reader = csv.DictReader(src)
data_cols = [c for c in reader.fieldnames if not c.startswith("sf__")]
with open(retry_path, "w", newline="", encoding="utf-8") as retry_f, \
open(review_path, "w", newline="", encoding="utf-8") as review_f:
retry_w = csv.DictWriter(retry_f, fieldnames=data_cols, lineterminator="\n")
review_w = csv.DictWriter(
review_f, fieldnames=["sf__Error"] + data_cols, lineterminator="\n"
)
retry_w.writeheader()
review_w.writeheader()
for row in reader:
code = row["sf__Error"].split(":", 1)[0].strip()
if code in RETRYABLE:
retry_w.writerow({c: row[c] for c in data_cols})
retry_count += 1
else:
review_w.writerow({"sf__Error": row["sf__Error"], **{c: row[c] for c in data_cols}})
review_count += 1
return retry_count, review_count
if __name__ == "__main__":
retry, review = split_failures("failed.csv", "retry.csv", "review.csv")
print(f"retry={retry} review={review}")The writer uses lineterminator="\n" so the file matches a job created with "lineEnding": "LF". If you created the job with CRLF, change both together. A mismatch between the declared line ending and the file is a common cause of a whole job failing on upload.
Unprocessed records
After a Failed or Aborted job, some rows were never attempted. They appear in neither the successful nor the failed file. Fetch them from the job's unprocessedrecords endpoint:
curl "$INSTANCE_URL/services/data/v62.0/jobs/ingest/$JOB_ID/unprocessedrecords/" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-o unprocessed.csvThis file contains only your original columns, so it can be uploaded as is. A complete accounting of a job is therefore three files that should add up to your input row count: successful, failed and unprocessed. Checking that sum catches lost rows early.
Retrying safely
Follow these rules when you automate retries.
- Cap the attempts. Three rounds is a reasonable starting point. After the cap, write the remaining rows to the review file.
- Wait between rounds. Lock contention usually clears when other transactions finish, so sleep for a growing delay such as 30, 60, then 120 seconds.
- Shrink the problem. Each round resubmits only the retryable rows, so each job is smaller than the last. If the retry set stays about the same size across rounds, the cause is not transient and you should stop.
- Check that retries make progress. Compare the retry count with the previous round. A count that does not fall means you are repeating the same failure.
- Make the load idempotent where you can. An
upsertkeyed on an external ID is safe to run twice, because a row that already landed is updated instead of duplicated. With plaininsert, the only protection against duplicates is sending the right rows.
For lock errors, the better fix is upstream. Sort the CSV by the parent record, such as AccountId, so rows that touch the same parent are processed together instead of competing across batches. Chapter-level practices for this appear in the performance chapter.
Job-level failures and aborting
When a job is Failed, GET the job and read errorMessage. Typical causes are a header column that is not a field on the object, a header that does not match the external ID field for an upsert, or a CSV that cannot be parsed. Fix the file and create a new job. A closed job cannot be reopened.
To stop a job you no longer want, change its state to Aborted while it is Open, UploadComplete or InProgress:
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"}'Records already committed stay committed. Abort does not roll them back, so fetch the successful and unprocessed files before deciding what to resubmit.
Common mistakes
- Uploading
failedResultswithout removingsf__Idandsf__Error. - Retrying every failure, including validation errors, until the attempt cap is reached.
- Resubmitting the full original file after a partial run.
- Treating
JobCompleteas success without checking the failed count. - Opening the CSV in a spreadsheet and saving it. This can change line endings, drop leading zeros, and reformat dates.
Exercise
A 100,000-row insert job finishes in state JobComplete with numberRecordsFailed = 400. Of the failed rows, 350 have UNABLETOLOCKROW and 50 have REQUIREDFIELD_MISSING. What do you upload next, which columns must the file contain, and why shouldn't you resubmit the whole original file?
Show answer
Upload a new job containing only the 350 UNABLETOLOCKROW rows, after a delay. Build it from failedResults by dropping sfId and sfError, so the header holds only the original upload columns. The 50 REQUIREDFIELD_MISSING rows need corrected data and go to a review file, because retrying them fails the same way. Resubmitting the full file would insert the 99,600 successful rows a second time and create duplicates.
Exercise
A job ends in state Aborted after 60,000 of 100,000 rows were attempted. Which three result sets should you collect, and what check confirms nothing was lost?
Show answer
Collect successfulResults, failedResults and unprocessedrecords. The three row counts must add up to the 100,000 input rows. Unprocessed rows can be uploaded directly because they contain only the original columns, and failed rows go through the classify-and-strip step first.