Design a Two-Way Sync Engine Between a Platform and External SaaS Tools
System DesignModel answerLast updated
Design a system that keeps records in sync across a central platform and multiple third-party SaaS integrations, handling conflicts, retries, and rate limits reliably.
Scenario
You are building the backend for a work-management platform that integrates with external SaaS tools like project trackers, CRMs, and code repositories. Users interact with records inside your platform, but those same records are mirrored in one or more external tools. Changes can happen on either side at any time.
Your job is to design the sync engine that keeps everything consistent.
Functional Requirements
- Two-way propagation. A change made inside your platform should appear in the connected external tool, and a change made in the external tool should appear in your platform.
- Conflict handling. When the same record is modified on both sides before either change has synced, the system must detect and resolve the conflict without silently dropping data.
- Idempotent operations. Network failures will cause retries. A retried operation must not create duplicates or apply the same change twice.
- Scale. Support tens of thousands of active connections, each potentially receiving bursts of thousands of changes in a short window.
Non-Functional Requirements
- No updates should be lost during partial outages or provider downtime.
- Propagation latency should be sub-second where the external API supports webhooks and has rate-limit headroom.
- OAuth tokens and other credentials must be stored and accessed securely.
What to Cover
- A component-level architecture for both the outbound path (platform → external) and the inbound path (external → platform).
- How you detect and prevent sync loops, where a change bounces back and forth indefinitely between the two sides.
- Your conflict detection and resolution strategy, with trade-offs between approaches.
- How you guarantee idempotency on creates and updates in both directions.
- How you handle rate limits imposed by external APIs, including bursts from bulk operations.
- A data model that tracks sync state, pending operations, and conflicts.
Hints
Hint 1
The external API is the weakest link. Webhooks can be delayed, duplicated, or missing entirely — design the inbound path assuming the webhook payload alone is not trustworthy. Re-fetching the current remote state before processing is safer than trusting the payload.
Hint 2
Whole-record last-write-wins is easy to implement but silently drops data when two fields are edited concurrently on different sides. Think about whether you can do a per-field merge against a stored base snapshot instead.
Hint 3
A sync loop is easy to miss during design. Trace the full round-trip: platform write → push to external → external fires webhook → inbound worker → platform write → outbox event → push again. Identify exactly where you break the cycle and make it reliable under retries.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Scope and Scale Assumptions
State these upfront before drawing anything.
- ~5,000 tenants, ~20,000 active connections (one connection = one tenant linked to one external account).
- Up to 50,000 synced records per connection → roughly 1B record-link rows. At ~300 bytes each, sync metadata is around 300 GB — manageable with a sharded relational store.
- Average change rate: ~1 event/connection/minute → ~350 events/s sustained. Peak is 10× that (~3–5k/s), and bursts are highly skewed — one bulk operation can emit 10,000 events for a single connection in under a minute.
- Consistency target: eventual consistency, zero lost updates, per-entity ordering within a connection.
The most important thing to say early: external APIs are the bottleneck and the least reliable component. They have rate limits, no transactions, often no idempotency support, and their webhooks are thin, duplicated, and out of order. The entire design is organized around that constraint.
2. High-Level Architecture
Outbound path (platform → external)
- The platform API writes the entity row and an outbox row in a single DB transaction. This is the transactional outbox pattern — it eliminates the dual-write window where a crash between "write entity" and "publish event" would silently drop the change.
- A CDC relay or outbox poller publishes the event to a message queue (e.g., Kafka). Partition by
hash(connection_id, entity_id)to preserve per-entity ordering without global ordering overhead. - Outbound sync workers consume events, coalesce rapid-fire changes to the same entity into a single call, acquire a rate-limit token, then invoke the appropriate connector adapter.
- The connector adapter translates the canonical data model to the provider's schema and makes the API call.
- On success, the worker updates
entity_linkswith the newremote_version(etag, revision, orupdated_at).
Inbound path (external → platform)
- A webhook receiver verifies the HMAC signature, writes the raw event to an inbound queue, and returns HTTP 200 within ~200 ms. Never do real work synchronously here.
- Inbound workers deduplicate the event, then — critically — re-fetch the current state of the record from the external API rather than trusting the webhook payload. Payloads are often partial or stale.
- Workers run the conflict resolver, then write to the platform with
origin = connection_idtagged on the write. - Providers without webhooks are covered by a poller scheduler that tracks a cursor per connection and polls on a cadence proportional to the connection's activity level.
Supporting components
- Token vault: OAuth tokens encrypted with a per-tenant key managed by a KMS. A refresh service rotates tokens before expiry. Workers fetch plaintext in memory only — tokens never appear in logs or queues.
- Rate limiter: token buckets in Redis, one bucket per connection, seeded from provider-specific config.
- Delay queue / DLQ: exponential backoff for transient failures; poison-message handling for permanent ones.
- Reconciler: a background job that periodically compares hashes of local and remote state to catch drift that escaped event-driven processing.
3. Data Model
connections(
connection_id PK, tenant_id, provider, credential_ref,
poll_cursor, rate_limit_cfg JSONB, status, health_at
)
entity_links(
connection_id, local_id, remote_id, entity_type,
local_version BIGINT, -- version last confirmed synced
remote_version TEXT, -- etag / revision / updated_at
base_snapshot JSONB, -- last agreed state, used for 3-way merge
last_pushed_hash TEXT, -- hash of the last payload we sent
last_synced_at TIMESTAMPTZ,
sync_state TEXT, -- idle | pending | conflict
PRIMARY KEY (connection_id, local_id),
UNIQUE (connection_id, remote_id)
)
outbox(
event_id PK, entity_id, version, origin,
changed_fields TEXT[], created_at
)
sync_ops(
op_id PK, idempotency_key UNIQUE, connection_id, local_id,
direction TEXT, payload JSONB, state TEXT,
attempts INT, next_attempt_at TIMESTAMPTZ, last_error TEXT
)
conflicts(
conflict_id PK, connection_id, local_id, field,
local_val JSONB, remote_val JSONB, base_val JSONB,
status TEXT, resolved_by TEXT
)
Shard by tenant_id or connection_id so that all sync state for a single connection lands on the same shard, keeping joins cheap.
4. Sync Loop Prevention
Without explicit suppression, this cycle runs forever: platform write → push to external → external webhooks back → inbound worker writes to platform → outbox event → push again.
Two layers break it:
- Origin tagging. Inbound writes record
origin = connection_id. Outbound workers skip re-sending an event to the connection it arrived from. The event can still fan out to other connections (e.g., a GitHub connection watching the same record). - Echo detection. After each outbound push, store
last_pushed_hashand theremote_versionreturned. When a webhook arrives and the re-fetched content hash matcheslast_pushed_hash, it is our own echo — advanceremote_versionand discard the event.
Both layers are needed. Origin tagging alone fails when a retry races with the incoming webhook. Echo detection alone fails when two rapid changes produce the same hash by coincidence.
5. Conflict Detection and Resolution
Provider APIs expose only an etag, a revision number, or updated_at — not vector clocks. The strategy is optimistic concurrency plus a per-field three-way merge against base_snapshot.
Detection:
- Outbound: send
If-Match: remote_versionwhere the provider supports it; otherwise read-before-write and compare. - Inbound: check whether
local_versionhas advanced since the last sync before writing.
Resolution — per field against base:
- Only one side changed a field → take that side's value.
- Both sides changed a field to the same value → no-op.
- Both sides changed a field to different values → apply a configured policy:
- Last-writer-wins on server timestamps. Simple, but clock skew can cause surprises. Prefer the provider's server time, not the client's.
- Designated source of truth. E.g., "the CRM owns the
amountfield." Explicit and predictable. - Raise a conflict row. Surface it in the UI for a human to resolve.
- Commutative fields (label lists, comment threads) merge as set union or append rather than overwrite.
The common mistake to call out: whole-record LWW is simple but silently discards data whenever two different fields are edited concurrently. Field-level three-way merge against base_snapshot is the correct default.
6. Idempotency
Outbound:
- Derive
idempotency_key = hash(connection_id, local_id, local_version, op_type)and enforce a unique constraint onsync_ops.idempotency_key. A duplicate event that slips through the queue is rejected at the DB level. - Updates are naturally idempotent when they send absolute values rather than increments.
- Creates are the dangerous case. Use the provider's idempotency header when available. Otherwise, stamp
local_idinto a custom external-ID field on the remote record. Before retrying a create with an unknown outcome, search the provider by that ID first.
Inbound:
- Deduplicate on
(connection_id, remote_id, remote_version). Discard any event whoseremote_versionis older than or equal to what is stored inentity_links.
7. Rate Limit Handling
- Token buckets in Redis, one per connection, configured per provider (e.g., 10 req/s for one provider, 5 req/s for another). Workers acquire a token before each call.
- Adaptive back-pressure. On a 429 response, parse
Retry-Afterand pause that connection's worker for the indicated duration. Do not discard the event — re-enqueue with a delay. - Bulk coalescing. For connections emitting high-frequency updates to the same entity, hold events in a short coalesce window (e.g., 500 ms) and send only the latest version. This converts N API calls into 1.
- Prioritization. Interactive user-initiated changes jump ahead of background reconciliation jobs in the queue. A user clicking "save" should not wait behind a 10,000-item bulk sync.
Common Mistakes to Avoid
- Dual-write without an outbox. Writing the entity and then publishing an event are two separate operations. A crash between them drops the event silently. Use the transactional outbox pattern.
- Trusting webhook payloads. Webhooks are delivery guarantees, not data guarantees. Always re-fetch.
- Ignoring the loop. Sync loops are easy to miss and catastrophic in production. Trace the full round-trip during design.
- Whole-record LWW. It feels safe but loses concurrent field edits. Per-field merge is worth the added complexity.
- Logging tokens. Credentials serialized into queue payloads or log lines are a serious security incident. Pass only a
credential_refthrough the pipeline.