Need help in writing logic for below requirement.

I have a custom object and a web service is enabled to insert data into it from external system. Inside the service we have a logic to validate if similar record is already existing (we use multiple parameters to compare), we have to merge the new record to existing. I was able to achieve it by querying the object before insertion.

But the problem I see is, as its a web service, external system is calling the web services in bulk at once. Thus, in some situations where similar records being called through service at same time, we are not getting records while querying to validate our conditions and duplicates are getting inserted to system.

Also, if there are any data related errors etc, I need to respond back in the web service.

Whats the best way / place to put these validations / the logic?

1 Answer 1


With your approach you're likely to get Query Timeout Exception since you'll need to retrieve all records from the database to detect duplicates.

Best way would be to use declarative approach by utilizing Matching and Duplicate rules provided by Salesforce. Follow below steps:

  1. Create a matching rule with appropriates filters to detect duplicates.

  2. Create a duplicate rule and add the matching rule which you've created.

  3. Once done, activate matching rule and duplicate rule.

With these simple 3 steps you can detect duplicate rules and execute actions accordingly. Refer this Matching and duplicate rules documentation.

  • 2
    this is good idea, but duplicate and matching rules don't compare records, that are in chunk of bulk transaction anyway Commented Jul 3, 2017 at 10:25
  • @AlexanderBerehovskiy you have any link for this behavior ? Commented Jul 3, 2017 at 10:27
  • @AlexanderBerehovskiy Recently I was consuming JSON through REST API which had a bulk of records and I was able to detect duplicate records. Can you share any link or documentation. Commented Jul 3, 2017 at 10:29
  • that had such behavior at late 2015, let me check maybe it is fixed now and I am mistaken Commented Jul 3, 2017 at 10:30
  • 1
    @RohitMourya thanks for the suggestion. And, thanks #AlexanderBerehovskiy for analyzing the suggestion. We created a custom field which is set to unique and inserted our duplicate criteria fields into it by concatenating them(field1__C+field2__C etc..), thus it throwing exception on duplicate record and we are handling the exception to merge the record.
    – Lucky
    Commented Jul 14, 2017 at 2:50

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .