How can we sync the objects across 2 Salesforce ORGS?

Requirement

A company may have two (or more) Salesforce orgs for several strategic, operational, or technical reasons like Mergers & Acquisitions, Business Unit or Subsidiary Separation, Security & Data Isolation Requirements, Performance and Scalability or Org Specialization. This will lead to synchronize the data between the orgs. Here we will evaluate best options to achieve the same.

Solution

Approach 1: Salesforce to Salesforce integration

Salesforce-to-Salesforce (S2S) is a native feature that allows two Salesforce orgs to share records (e.g., Leads, Opportunities, Cases) securely and bi-directionally, without middleware or custom code.

https://help.salesforce.com/s/articleView?id=sales.business_network_intro.htm&language=en_US&type=5

Approach 2: Using Third Party tool or connector

The third-party option is easier than coding. There are many that offers a no-code or low-code solution like Skyvia, Zapier or Mulesoft etc. However it will require recurring cost and proper error control.

Approach 3: Custom – using APEX code and Salesforce REST API.

EX. The scenario is you will run the code in your ORG and access the remote ORG. So, you need its URL and access token. Here’s a sample APEX code that will sync the Account object:

public class SalesforceObjectSync {

// Remote Salesforce org credentials
private static final String REMOTE_INSTANCE_URL = 'https://remote-org.my.salesforce.com';
private static final String ACCESS_TOKEN = 'YOUR_REMOTE_ORG_ACCESS_TOKEN';

// Method to fetch Accounts from the local org
public static List<Account> getLocalAccounts() {
    return [SELECT Id, Name, Industry, Phone, Website FROM Account];
}

// Method to sync Accounts to the remote org
public static void syncAccountsToRemoteOrg() {
    List<Account> localAccounts = getLocalAccounts();
    for (Account acc : localAccounts) {
        syncAccountToRemoteOrg(acc);
    }
}

// Method to sync a single Account to the remote org
private static void syncAccountToRemoteOrg(Account acc) {
    Http http = new Http();
    HttpRequest req = new HttpRequest();
    req.setEndpoint(REMOTE_INSTANCE_URL + '/services/data/v52.0/sobjects/Account');
    req.setMethod('POST');
    req.setHeader('Authorization', 'Bearer ' + ACCESS_TOKEN);
    req.setHeader('Content-Type', 'application/json');
    req.setBody(JSON.serialize(acc));

    try {
        HttpResponse res = http.send(req);
        if (res.getStatusCode() == 201) {
            System.debug('Account synced successfully: ' + acc.Name);
        } else {
            System.debug('Failed to sync Account: ' + acc.Name + '. Status: ' + res.getStatusCode() + ' Response: ' + res.getBody());
        }


     } catch (Exception e) {
            System.debug('Error syncing Account: ' + acc.Name + ' Error: ' + e.getMessage());
        }
    }
}