Prompt
How do I build a two-way sync between my app and Salesforce?
Latest observation
Building a two-way sync between your app and Salesforce usually means:
- changes in your app update Salesforce
- changes in Salesforce update your app
- both systems stay aligned without loops, duplicates, or conflicts
The exact design depends on your data model and latency needs, but the core pattern is the same.
1) Start by defining the sync contract
Before writing code, decide:
- Which objects sync? (Lead, Contact, Account, custom objects, etc.)
- Which fields are source of truth?
- Which direction wins when both change?
- How fast does sync need to happen?
- real-time
- near real-time
- batch / periodic
- How will you match records across systems?
- Salesforce Id stored in your DB
- external ID in Salesforce
- both
A good rule:
- one system should own each field if possible
- two-way sync is easier when ownership is explicit
2) Add an external ID on the Salesforce side
Create a custom field in Salesforce like:
External_App_Id__con the object you sync
Mark it as:
- External ID
- optionally Unique
This lets you:
- upsert records from your app into Salesforce
- reliably match the same record across systems
If your app has a stable primary key, use that as the external ID.
3) Decide on the sync architecture
The most common architecture is:
A. Your app sends changes to Salesforce
Use Salesforce REST API:
- Upsert by external ID
- Create if needed
- Patch for updates
B. Salesforce sends changes to your app
Use one of:
- Change Data Capture (CDC) for near real-time events
- Platform Events
- Outbound Messages from workflow/Flow
- Polling via SOQL +
SystemModstampif you can tolerate delay
For most modern systems:
- App → Salesforce: REST API upsert
- Salesforce → App: CDC / Platform Events
4) Use an event-driven sync pipeline
A robust setup usually looks like this:
Outbound from app
- User changes data in your app
- Your app writes to its own DB
- App publishes a change event or stores it in an outbox table
- Sync worker pushes to Salesforce
- Salesforce returns its record Id
- Store mapping in your DB
Inbound from Salesforce
- Salesforce emits CDC / event
- Your webhook or listener receives event
- You map Salesforce Id to your app record
- Apply update to your DB
- Mark sync state / audit trail
This decouples user actions from API calls and makes retries easier.
5) Prevent infinite update loops
This is one of the biggest problems in two-way sync.
Example loop:
- app updates Salesforce
- Salesforce event comes back
- app applies same change
- app pushes again
- repeat
To prevent this, use one or more of:
A. Sync metadata
Store fields like:
last_synced_atlast_synced_bylast_sync_sourcesalesforce_last_modifiedapp_last_modified
B. Ignore self-generated changes
If you updated Salesforce, include a marker, then ignore the resulting echo event if possible.
C. Compare payload hashes
If inbound data matches what you already have, do nothing.
D. Use field ownership rules
Only sync fields that are allowed to change from that direction.
6) Handle conflicts explicitly
You need a conflict policy. Common options:
Option 1: Last write wins
Simplest, but can lose data.
Option 2: Source-of-truth by field
Example:
- app owns
internal_status - Salesforce owns
sales_owner - both may own different fields
Option 3: Human review
For important records, flag conflicts for manual resolution.
Option 4: Timestamp-based merge
Use updated_at / SystemModstamp, but be careful with clock skew and retries.
A practical approach:
- use field ownership
- use last-write-wins within owned fields
- log conflicts for rare edge cases
7) Choose the Salesforce APIs/features
For writing to Salesforce
- REST API
- Composite API if you need multiple related writes in one request
- Bulk API 2.0 for large batches
- Upsert by external ID for matching
For receiving changes from Salesforce
- Change Data Capture (CDC): best for record-level updates
- Platform Events: best for custom business events
- Streaming API / PushTopic: older pattern, less preferred now
- Polling: fallback when eventing isn’t possible
8) Build retry, idempotency, and dead-letter handling
Your sync will fail sometimes due to:
- API limits
- validation rules
- network issues
- bad data
- permission changes
So make it resilient:
Retry safely
- exponential backoff
- retry transient failures only
Make writes idempotent
- use external IDs
- include a request id or sync id
- avoid creating duplicates on retry
Dead-letter queue
If a record repeatedly fails:
- move it to a failed-sync queue
- alert someone
- allow manual replay after fix
9) Keep mappings and sync state
Store a mapping table in your app or integration service:
app_record_idsalesforce_record_idobject_typelast_synced_atlast_synced_hashsync_statuslast_error
This helps you:
- find the right record quickly
- avoid duplicates
- debug issues
- resume after outages
10) Watch out for Salesforce-specific constraints
Common Salesforce limits and quirks:
- API call limits
- governor limits in Apex
- field validation rules
- required fields
- sharing and permissions
- record lock contention
- bulk processing constraints
- eventual consistency in some event flows
Design your sync around these:
- batch when possible
- validate before sending
- use integration users with correct permissions
- monitor API usage
11) Recommended implementation pattern
A strong, common pattern is:
In your app
- DB transaction writes data
- write a change record to an outbox table
- background worker processes outbox
- worker upserts to Salesforce
- store returned Salesforce Id
From Salesforce
- enable Change Data Capture
- subscribe via a middleware service
- translate events into app updates
- store processed event ids for deduplication
This is often more reliable than trying to do direct synchronous writes everywhere.
12) Minimal architecture example
Data flow
- App UI → App DB
- App DB → Outbox
- Outbox worker → Salesforce REST API
- Salesforce CDC → Integration service → App DB
Core rules
- each record has both IDs stored
- each update has a source marker
- retries are idempotent
- conflicts are resolved by policy
13) Pseudocode for app → Salesforce
def sync_to_salesforce(app_record):
sf_id = lookup_salesforce_id(app_record.id)
payload = {
"External_App_Id__c": app_record.id,
"Name": app_record.name,
"Email": app_record.email,
}
if sf_id:
salesforce.patch(f"/sobjects/Contact/{sf_id}", payload)
else:
result = salesforce.upsert(
"/sobjects/Contact/External_App_Id__c/" + app_record.id,
payload
)
save_salesforce_id(app_record.id, result["id"])
14) Pseudocode for Salesforce → app
def handle_salesforce_event(event):
if already_processed(event.id):
return
sf_id = event.record_id
app_id = lookup_app_id_by_salesforce_id(sf_id)
if not app_id:
app_id = create_app_record_from_salesforce(event.data)
else:
update_app_record(app_id, event.data)
mark_processed(event.id)
15) Test cases you should cover
- create in app, appears in Salesforce
- update in app, changes in Salesforce
- update in Salesforce, changes in app
- simultaneous update in both systems
- delete in one system
- duplicate event delivery
- retry after API failure
- mapping missing
- validation rule failure
- large batch sync
- permission denied
16) Practical recommendation
If you want the most reliable path:
- use external IDs
- use outbox pattern in your app
- use Salesforce CDC for inbound sync
- store record mappings
- define field ownership
- implement idempotency + retries
- add conflict handling and monitoring
If you want, I can also give you:
- a reference architecture diagram,
- a step-by-step implementation using Node.js/Python, or
- a Salesforce-specific design for Contacts/Leads/Accounts.