A payment webhook fires twice, your Node.js worker retries after a timeout, and Salesforce now holds two Opportunity records for one invoice. Reps then see inflated pipeline, and finance sees double revenue. This happens wherever a service writes over the REST API without a stable key, usually in webhook consumers and queue workers that retry on failure. Retries are routine in distributed systems, so these duplicates keep coming. The fix is to stop creating records and start upserting them against an external ID. This article shows how Salesforce integrations work in production with a retry-safe Node.js client, covering field setup, the upsert call, and retry rules.
Context and Setup
A safe retry needs three things: a unique external ID field, a stable key from the source system, and a policy that repeats only errors that are safe to repeat.
You need Node.js 18 or later (for built-in fetch), an OAuth access token from a connected app, and API version 61.0. Retries also cost quota. API Request Limits documentation states that the daily allocation applies to the whole org, not per user. Its own example is an Enterprise Edition org with 15 licenses, which gets 115,000 requests per rolling 24 hours. Past that, calls fail with HTTP 403 and REQUEST_LIMIT_EXCEEDED.
How to Make Salesforce Writes Idempotent With External IDs
An idempotent write gives the same final state whether it runs once or five times. Upsert on an external ID provides that.
Step 1: Create a Unique External ID Field
A unique constraint lets the database reject duplicates even when two workers race.
Open Setup, then Object Manager, then Opportunity.
Create a Text(40) field named Billing_Ref__c.
Tick both External ID and Unique.
Step 2: Upsert by Key in Node.js
A PATCH request to an external ID path creates the record if the key is new and updates it if the key exists.
js
// upsert.js (Node.js 18+, built-in fetch)
const API = 'v61.0';
export async function upsertOpportunity(ctx, invoice) {
// Why: the invoice ID is the idempotency key, so a retry updates instead of duplicating
const url = ${ctx.instanceUrl}/services/data/${API} +
/sobjects/Opportunity/Billing_Ref__c/${encodeURIComponent(invoice.id)};
const res = await fetch(url, {
method: 'PATCH', // Why: PATCH on an external ID path is the REST upsert
headers: {
Authorization: Bearer ${ctx.accessToken},
'Content-Type': 'application/json',
},
// Why: the key is already in the URL, so it stays out of the body
body: JSON.stringify({
Name: Invoice ${invoice.id},
Amount: invoice.amount,
StageName: 'Closed Won',
CloseDate: invoice.paidOn, // YYYY-MM-DD
}),
});
// 201 means created, 204 means updated
if (res.status === 201 || res.status === 204) return res.status;
const errors = await res.json().catch(() => []);
throw Object.assign(new Error('Salesforce upsert failed'), { status: res.status, errors });
}
Step 3: Retry Only Safe Errors
Retry only errors that clear on their own. Row locks clear in milliseconds, while a quota error clears in hours.
js
const RETRYABLE = new Set(['UNABLE_TO_LOCK_ROW', 'SERVER_UNAVAILABLE']);
export async function withRetry(fn, max = 4) {
for (let attempt = 0; ; attempt++) {
try {
return await fn();
} catch (err) {
const code = err.errors?.[0]?.errorCode;
// Why: fetch throws TypeError on network failure, and upsert makes that retry safe
const safe = RETRYABLE.has(code) || err.status >= 500 || err instanceof TypeError;
// Why: REQUEST_LIMIT_EXCEEDED will not clear in seconds, so retrying only burns quota
if (!safe || attempt >= max) throw err;
// Why: jitter stops parallel workers from retrying in lockstep and re-locking the row
const delay = Math.min(8000, 250 * 2 ** attempt) * (0.5 + Math.random());
await new Promise((r) => setTimeout(r, delay));
}
}
}
Trade-offs:
Upsert versus query-then-insert: the query adds a second API call and leaves a race window between the check and the write.
Single upsert versus sObject Collections: collections handle up to 200 records per call and save quota, but you must read per-record results, since one bad row no longer fails the whole request.
Real-World Application
In one of our projects at Oodles, a real estate synced 1000 invoices per day from a quickbooks into Opportunities through a Node.js worker. Timeout retries created duplicate records at a rate of 70 percent. We added the unique external ID, switched inserts to upserts, and batched writes through sObject Collections with the retry policy above.
Key Takeaways
A unique external ID field turns a database constraint into your last line of defense against duplicate writes.
PATCH on an external ID path gives you one-call upsert, so no read-before-write race exists.
Quota errors and lock errors need different retry rules, because one clears in milliseconds and the other in hours.
Collections cut call counts, at the cost of per-record error handling.
Questions or edge cases from your own integration? Share them in the comments, or talk to us about Salesforce integration work.
How do I prevent duplicate records in the REST API?
Add a unique external ID field, store the source system's stable key in it, and write with PATCH on the external ID path. Retries then update the existing record, and the unique constraint blocks races between workers.
Should I retry REQUEST_LIMIT_EXCEEDED?
Not quickly. It returns HTTP 403 when the rolling 24-hour allocation or the concurrent long-running request cap is hit. Queue the work, check the /limits resource, and resume once usage falls back under the allocation.
What is the difference between insert and upsert in It?
Insert always creates a record. Upsert checks an ID or external ID, then updates the match or creates a new record. Upsert is the safer choice for integrations that may deliver the same message more than once.
How many records can one Salesforce API call upsert?
sObject Collections accept up to 200 records per call. For larger loads, Bulk API 2.0 processes records asynchronously in jobs, which suits migrations better than real-time sync. Poll the job for results.
Why does Salesforce return UNABLE_TO_LOCK_ROW?
Concurrent transactions are updating the same record or a shared parent, such as many Opportunities under one Account. Retry with jittered backoff, and serialize writes per parent key when contention persists.
Top comments (0)