function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Eva Diaz 9Eva Diaz 9 

API Rest Contact integration problem: duplicated record error


We have a custom rest service in Salesforce invoked by another external system to upsert contacts. This service is invoked by POST method, and then it makes an upsert operation of the record received, which is identified in the json by a custom field checked as External ID.

The service is invoked from different events sending different data of the same record, and each event is a different request to the service.
Those events are sent at the same time and we cannot control the order.
For example, we have 4 requests of the same record, one at 15:15:30.539, other at 15:15:31.385, other at 15:15:31.443 and the last one at 15:15:31.444.
The point is, the first request returns an OK and the Salesforce Id of the contact created, but then the rest of requests return the next error: "errorMessage":"duplicate value found: User_External_Id__c duplicates value on record with id: 0037Z00001gvEdZ".

We have tried all different requests of each event separately via Postman, and everything works perfect, it first creates the record and then just update, as expected.

I can't understand why it isn't working when the requests are at the same time, when the dml operation is always an upsert, so it should never detect a duplicate. What do you think could be the problem?

Thank you in advance.
Bryan Leaman 6Bryan Leaman 6

I suspect the problem is essentially a race condition. The upsert operation is begun in all 4 requests before the first one finishes committing the change to the database. Under the hood, since you're upserting via an external Id, each request has to see if that Id is already assigned to a record. That part completes in all 4 requests before the first one actually writes & commits the new record. The way you describe it indicates an internal salesforce timing issue, which to me means there likely won't be a simple solution.

You could try simply adding a try-catch block around each upsert and if it fails because of a duplicate external Id, simply try the exact same upsert again.