# Sync Strategies

Keep customer data synchronized between your platform and AIDP.

## Sync Strategies

### 1. Real-Time Sync

Sync changes immediately as they occur.

**Pros**: Always up-to-date\
**Cons**: Higher API usage

```typescript
// On business update in your platform
async function onBusinessUpdate(businessId, changes) {
  await partner.sync.business(businessId, changes);
}
```

### 2. Scheduled Sync

Sync on a schedule (hourly, daily, etc.).

**Pros**: Lower API usage\
**Cons**: Potential data lag

```typescript
// Run every hour
cron.schedule('0 * * * *', async () => {
  const changes = await getChangedBusinesses(lastHour);
  await partner.sync.batch(changes);
});
```

### 3. Hybrid Sync

Real-time for critical changes, scheduled for bulk updates.

**Pros**: Balance of freshness and efficiency\
**Cons**: More complex

```typescript
// Real-time for critical fields
async function onCriticalUpdate(businessId, changes) {
  if (isCritical(changes)) {
    await partner.sync.business(businessId, changes);
  } else {
    await queueForBatchSync(businessId, changes);
  }
}
```

***

## Sync Implementation

### Track Changes

```typescript
// Track last sync time per customer
const syncState = new Map();

async function syncCustomer(customerId) {
  const lastSync = syncState.get(customerId) || 0;
  const changes = await getChanges(customerId, lastSync);

  if (changes.length > 0) {
    await partner.sync.incremental(customerId, changes);
    syncState.set(customerId, Date.now());
  }
}
```

### Handle Conflicts

```typescript
async function resolveConflict(local, remote) {
  // Last-write-wins
  if (local.updatedAt > remote.updatedAt) {
    return local;
  }

  // Or merge changes
  return {
    ...remote,
    ...local,
    updatedAt: Math.max(local.updatedAt, remote.updatedAt),
  };
}
```

***

## Webhooks

### Subscribe to AIDP Changes

```typescript
await partner.webhooks.create({
  url: 'https://yourplatform.com/webhooks/aidp',
  events: ['business.updated', 'business.deleted'],
});
```

### Handle Incoming Changes

```typescript
app.post('/webhooks/aidp', async (req, res) => {
  const event = req.body;

  if (event.type === 'business.updated') {
    await updateLocalBusiness(event.data);
  }

  res.status(200).send('OK');
});
```

***

## Monitoring

### Sync Status

```typescript
const status = await partner.sync.status(customerId);

console.log(`Last sync: ${status.lastSync}`);
console.log(`Pending changes: ${status.pendingChanges}`);
console.log(`Failed syncs: ${status.failedSyncs}`);
```

### Sync Metrics

```typescript
const metrics = await partner.sync.metrics({
  startDate: '2024-01-01',
  endDate: '2024-12-31',
});

console.log(`Total syncs: ${metrics.totalSyncs}`);
console.log(`Success rate: ${metrics.successRate}%`);
console.log(`Avg sync time: ${metrics.avgSyncTime}ms`);
```

***

**Next**: [Partnership Program →](https://amistan.gitbook.io/aidp-docs/for-saas-platforms/partnership)
