Sub topic 15
Performance and lock contention practices
This chapter assumes you can already run the full ingest cycle from earlier chapters. That means creating a job, uploading CSV, setting UploadComplete, polling, and reading failedResults. It also assumes you know the basics of lookup and master-detail relationships. Here you will learn why a correct load can still be slow or fail with lock errors, and what you can change in your data and your org to fix that.
Where bulk load time goes
Bulk API 2.0 splits your upload into internal batches and processes them in parallel. You can't set the batch size or choose serial processing. Bulk API 1.0 had a serial concurrency mode for this purpose, and 2.0 does not.
Your levers are therefore indirect:
- The order of rows in the file.
- The shape of the data, such as how many children point at one parent.
- The work Salesforce does per record, such as triggers, flows, and sharing recalculation.
- How many jobs run at once against the same objects.
Most slow loads trace back to the second and third items.
What a row lock is
When Salesforce writes a record, it locks that record until the transaction commits. Writing a child record can also lock related records:
- Inserting or updating a Contact locks its parent Account.
- A detail record in a master-detail relationship locks its master.
- Changing a record's owner can lock the old and new owner's sharing structures.
- Updating a record that has roll-up summary fields locks the parent that holds the roll-up.
Because batches run in parallel, two batches may both need the same parent at the same moment. The second one waits. If the wait is too long, the rows fail with UNABLE_TO_LOCK_ROW. Salesforce may retry some of these internally. The rows that still fail show up in failedResults with that text in the sf__Error column.
Order rows by parent
Salesforce cuts your file into batches in file order. If child rows for the same parent are scattered across the file, many batches will touch that parent at once. If they are adjacent, nearly all rows for a parent land in one batch, and only the parents at batch boundaries are shared.
A sample input with the parent in an AccountId column:
FirstName,LastName,AccountId
Ada,Lovelace,001000000000002AAA
Alan,Turing,001000000000001AAA
Grace,Hopper,001000000000002AAA
Edsger,Dijkstra,001000000000001AAAThis script sorts any CSV by a column you name and keeps the LF line endings that the job in earlier chapters declared:
import csv
import sys
src, dst, key = sys.argv[1:4]
with open(src, newline="", encoding="utf-8") as f:
reader = csv.DictReader(f)
fieldnames = reader.fieldnames
rows = list(reader)
rows.sort(key=lambda row: row[key])
with open(dst, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=fieldnames, lineterminator="\n")
writer.writeheader()
writer.writerows(rows)
print(f"Wrote {len(rows)} rows sorted by {key}")Run it as python sort_csv.py contacts.csv contacts_sorted.csv AccountId. The script loads the whole file into memory. For files near the upload size limit this is usually fine on a modern machine. For larger source files, split the file first or use an external sort tool.
For other relationships, sort by the field that points at the shared record:
| Load | Sort by |
|---|---|
| Contacts into Accounts | `AccountId` |
| Opportunities into Accounts | `AccountId` |
| Detail records in master-detail | The master lookup field |
| Ownership changes | `OwnerId` |
| Child records with a self-lookup hierarchy | The parent lookup, loading parents first |
Watch for data skew
Sorting helps only if no single parent has an enormous number of children. Two common cases:
- Parent skew: one record, such as a catch-all Account, has tens of thousands of children. Any update to a child contends for that parent. Salesforce's guidance is to avoid more than about 10,000 children under one parent.
- Ownership skew: one user owns a very large number of records. Ownership changes and sharing recalculation then become slow and lock-prone.
If you must load skewed data, spread children over several placeholder parents. Alternatively, load the skewed group in its own job at a quiet time, with nothing else running against that object.
Reduce per-record work
Each row runs through the full save logic: validation rules, triggers, flows, duplicate rules, and sharing. Any of those can lengthen a transaction, and longer transactions hold locks longer.
- Check automation before the load. List the active triggers, flows, and workflow rules on the object. Slow or non-bulk-safe automation is the most frequent cause of lock errors in large loads.
- Add a bypass. If the business allows it, add a custom setting or custom permission that automation checks, and set it for the integration user during the load. Remove it afterward.
- Defer sharing calculations. Your admin can suspend sharing rule recalculation for a very large load, then resume it afterward. Check the current setup options and permissions in your org before relying on this.
- Load only the columns you need. Extra columns still have to be parsed and mapped.
- Prefer IDs to relationship names. A column such as
AccountIdis cheaper than resolving a parent through an external ID relationship column on every row. If the parent IDs are not known, export them once with a bulk query and join locally.
Control concurrency yourself
Bulk API 2.0 parallelizes inside a job. It does not coordinate with your other jobs. Two jobs on the same object, or on objects with a shared parent, will contend as badly as two batches in one job.
- Run one load job per object at a time.
- Load parents before children, and wait for the parent job to reach
JobComplete. Then read its successful results to get the new IDs for the child file. - Don't run a bulk load while integrations, scheduled Apex, or other users do heavy writes on the same objects.
- Schedule large loads outside business hours.
Poll sensibly
Polling does not slow a job, but each call counts against API limits. A 10-second interval, as used in the earlier script, suits a job that takes minutes. For jobs that run for hours, back off to 30 to 60 seconds, as in this loop.
import time
def wait_for_job(get_state, start=5, ceiling=60):
delay = start
while True:
state = get_state()
if state in ("JobComplete", "Failed", "Aborted"):
return state
time.sleep(delay)
delay = min(delay * 2, ceiling)
# Demonstration with a fake job that finishes after four checks.
states = iter(["Open", "InProgress", "InProgress", "JobComplete"])
print(wait_for_job(lambda: next(states), start=0.01, ceiling=0.04))In your real script, get_state is a function that calls GET .../jobs/ingest/$JOB_ID and returns ["state"].
Retry lock failures separately
Failed rows are not all alike. Rows rejected by validation will fail again until you fix them. Rows that hit UNABLE_TO_LOCK_ROW should succeed on a retry. Separate the two groups so you retry only what can succeed.
This script reads failed.csv, as saved by the end-to-end script. It writes a clean file with just the lock failures, with the sf__ columns removed so it is a valid upload for a new job:
import csv
import sys
src, dst = sys.argv[1:3]
retry = other = 0
with open(src, newline="", encoding="utf-8") as f_in:
reader = csv.DictReader(f_in)
fields = [c for c in reader.fieldnames if not c.startswith("sf__")]
with open(dst, "w", newline="", encoding="utf-8") as f_out:
writer = csv.DictWriter(f_out, fieldnames=fields, lineterminator="\n")
writer.writeheader()
for row in reader:
if "UNABLE_TO_LOCK_ROW" in row["sf__Error"]:
writer.writerow({k: row[k] for k in fields})
retry += 1
else:
other += 1
print(f"{retry} rows to retry, {other} rows need data fixes")Submit the retry file as a new job. Keep the same sort order, and make sure no other job is running on the object. If the same rows keep failing, the cause is probably skew or automation, and retrying more will not help. In that case, split the retry file into smaller files and run them one after another.
A tuning checklist
- Is the file sorted by the parent or owner field?
- Does any parent have a very large number of children?
- Which triggers and flows run on this object, and are they bulk-safe?
- Is anything else writing to these objects during the load?
- Are parents loaded and complete before children start?
- Are lock failures separated from data failures before resubmission?
Exercise
A load of 2 million Contacts into existing Accounts finishes with about 3% of rows failed, and most sf__Error values say UNABLE_TO_LOCK_ROW. The input file is in the order the source system exported it, which is by CreatedDate. Name two changes you would make to the next run, and say what you would do with the failed rows from this run.
Show answer
First, sort the file by AccountId so contacts for the same account are adjacent and fall mostly into the same internal batch. Second, check for automation on Contact and Account (triggers, flows, roll-up summaries, sharing recalculation) and reduce or bypass it for the load, and make sure no other job or integration is writing to those objects at the same time. For the failed rows, filter failedResults to the ones with UNABLE_TO_LOCK_ROW, strip the sf__Id and sf__Error columns, keep them sorted by AccountId, and submit them as a new job. Rows with other errors need their data fixed first.