I'm working on an integration between Salesforce and SAP, where Quotes are being created simultaneously in Salesforce via an API. These Quotes are associated with the same customer, let's call it Customer1. When a Quote is created, an Apex trigger checks if there is an existing Opportunity related to Customer1. If no related Opportunity is found, the trigger creates a new Opportunity.
The issue arises when two Quotes are processed concurrently:
Quote1 for Customer1 is processed, and an SOQL query is executed to check if an Opportunity exists for Customer1. Quote2 for Customer1 is processed almost simultaneously, executing the same SOQL query. Since both queries run in parallel, they both return null, indicating that no Opportunity exists for Customer1. As a result, both processes proceed to create a new Opportunity, leading to duplicate Opportunities being created for the same customer. And also creating an opportunity takes 2-3 mins.(Considiring FOR UPDATE clause realases the lock after 10 secs as said in here )
What I've Tried: I researched potential solutions and came across the FOR UPDATE keyword in SOQL. My understanding is that it can lock the records during a transaction to prevent other operations from modifying them until the transaction completes. However, I'm unsure if this applies to my case since the Opportunity records don't exist at the time of the query.
My Question:
How can I prevent this race condition and ensure that only one Opportunity is created for Customer1, even when multiple Quotes are processed simultaneously? Is using FOR UPDATE the correct approach here, or is there a better way to handle this scenario in Apex? Any insights or suggestions would be greatly appreciated!
Similar cases:
What are race conditions in salesforce
How do I avoid race conditions when importing a large batch and running future methods?
unique
field to prevent record duplication on the DB level if that's the main concern.