I have a rest API endpoint in Salesforce which accepts a payload from my application. On reception of the first request with a given email, it creates a lead. On subsequent requests, it finds the lead and updates the lead with extra information in the payload. My problem is that if a user quickly moves through the process (like have most of the fields filled and they just click the next button, it is a wizard-like interface), I have to call the API in quick succession. While the first call is creating the lead, the second call searches for a lead with a given email (which is not created yet) and starts the call to create a new lead. In the meantime, the first call has finished creating the lead as well. Now I have 2 leads instead of one :(

Is there a way on the Salesforce side I can handle this? Can't change the way requests land, sorry.

1 Answer 1


Use the FOR UPDATE SOQL keyword in Apex to require row locks for the leads you're querying. This ensures that the lead query matching by email will wait for any other in-flight records. This will ensure that you're not creating duplicates, even if the records are inserted simultaneously between two API calls.

Lead[] existingLead = [SELECT Email FROM Lead WHERE Email = :incomingEmail FOR UPDATE];
  • wonderful, that inflight thing is what is messing it. I'll try this and report back! Jan 18, 2021 at 5:44
  • well, we tried (at least dev told me) and it is not working :( Feb 24, 2021 at 23:28
  • @TheVillageIdiot Maybe some Duplicate Rules, then? That is 100% reliable, but you'll have to deal with the errors.
    – sfdcfox
    Feb 25, 2021 at 3:00
  • That sounds good plan I've email and another unique piece of information and I don't want to have duplicate lead with email+uniquething combo! Voila, seems like a way out. On error go and query the existing lead. Feb 26, 2021 at 1:01

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.