Prompt
How do I set up two-way calendar sync in my product?
Latest observation
Two-way calendar sync is usually done by combining:
- Calendar provider APIs (Google Calendar, Microsoft Outlook / Microsoft Graph, sometimes CalDAV)
- A sync engine in your backend that tracks changes both ways
- A conflict strategy for simultaneous edits
Here’s the practical way to build it.
1) Decide your sync scope
First define exactly what “two-way sync” means for your product:
- Sync events only or also free/busy, reminders, attendees, locations, etc.
- Sync one calendar per user or multiple calendars
- Sync all events or only events created by your product
- Handle create, update, delete both directions
- Decide whether your app is the system of record for any fields
This matters because calendar sync gets complicated fast if you try to mirror everything.
2) Use provider OAuth + calendar APIs
For each provider:
- Google Calendar API
- Microsoft Graph Calendar API
You’ll need:
- OAuth login
- Long-lived refresh tokens
- Permission scopes that allow reading/writing calendars
Typical scopes:
- Google:
calendar,calendar.events - Microsoft:
Calendars.ReadWrite
Store tokens securely and encrypt them at rest.
3) Model your own internal calendar objects
Don’t sync directly provider-to-provider. Instead, keep your own internal representation:
usersconnected_accountscalendarseventsexternal_event_mappings
Each external event mapping should store:
- provider name
- provider calendar ID
- provider event ID
- your internal event ID
- last synced provider
etag/version/changeKey - last synced timestamp
- sync status
This lets you translate between systems and detect conflicts.
4) Set up change detection
For two-way sync, you need to detect changes from both sides.
Recommended approach
- From provider to your app: use webhooks / push notifications where available
- From your app to provider: write changes immediately through the provider API
- Periodic reconciliation: run a background poll as a fallback
Use:
events.watchfor push notificationssyncTokenfor incremental sync
Microsoft Graph
Use:
- subscription notifications
- delta queries for incremental sync
This is the standard pattern:
- initial full sync
- incremental sync thereafter
- occasional full resync if tokens expire
5) Build the sync flow
A reliable architecture looks like this:
A. Initial sync
- User connects calendar
- You fetch all existing calendars/events
- Save external IDs and metadata
- Mark a checkpoint for incremental sync
B. Inbound sync provider → your app
When the provider tells you something changed:
- Fetch changed events incrementally
- Compare against your DB
- Apply inserts/updates/deletes
- Record provider version/etag/change token
C. Outbound sync your app → provider
When a user creates/edits/deletes an event in your app:
- Update your internal DB first
- Queue a sync job
- Call provider API
- Save returned provider IDs/version info
- Mark synced
Use a queue so sync is resilient to API failures and rate limits.
6) Handle conflicts
Conflicts happen when the same event changes in both places before sync completes.
Common strategies:
Simple strategy: last write wins
- Compare timestamps
- Apply the newest change
- Easiest, but can overwrite user changes unexpectedly
Better strategy: field-level merge
- Merge non-overlapping changes
- Example: one side updates title, the other updates location
Best for UX: app-specific ownership
- Your app owns some fields
- The calendar provider owns others
- Example: title/time synced both ways, but internal notes only live in your app
If a conflict can’t be safely resolved, flag it for manual review.
7) Be careful with recurring events
Recurring events are one of the hardest parts.
You need to handle:
- recurring series master event
- exceptions / overridden instances
- deleted instances
- edits to a single occurrence vs the whole series
Make sure your internal model supports:
- recurrence rules
- series IDs
- exception IDs
- detached occurrences
If you skip this, sync will break quickly for real users.
8) Watch out for time zones and all-day events
Store event times in UTC internally, but preserve:
- original timezone
- all-day vs timed event
- provider-specific date semantics
All-day events are often date-based, not timestamp-based, so avoid converting them naively.
9) Deduplicate and prevent sync loops
A common bug:
- provider change comes in
- you write it to your DB
- your outbound sync sees it as a new local change
- it writes back to provider
- infinite loop
Prevent this by storing:
- origin of change
- sync source
- last synced provider version
- change fingerprint / hash
Only push outbound changes that originated locally.
10) Use idempotency and retries
Sync jobs should be safe to retry.
Best practices:
- generate idempotency keys for create/update requests where possible
- retry transient failures with exponential backoff
- handle 429 rate limits
- handle 5xx errors
- refresh expired OAuth tokens automatically
11) Deletions need special handling
Treat deletes carefully:
- soft-delete internally first
- sync delete to provider
- if provider delete comes in, soft-delete locally
- keep tombstones for some time so you don’t recreate deleted events
12) Minimal viable architecture
If you want a simple but solid MVP:
- OAuth connect with Google and Microsoft
- Initial full sync
- Incremental sync using webhook + delta/sync tokens
- Internal event store with external mappings
- Background job queue for outbound updates
- Conflict resolution with last-write-wins
- Retry + rate-limit handling
That gets you a real two-way sync system.
13) Suggested data model
Very simplified:
connected_accounts
- id
- user_id
- provider
- access_token_encrypted
- refresh_token_encrypted
- token_expiry
- sync_cursor
- webhook_subscription_id
calendars
- id
- connected_account_id
- provider_calendar_id
- name
- is_primary
events
- id
- calendar_id
- title
- description
- start_time_utc
- end_time_utc
- timezone
- all_day
- status
- updated_at
- deleted_at
external_event_mappings
- id
- event_id
- provider
- provider_calendar_id
- provider_event_id
- provider_etag
- provider_version
- last_synced_at
- source_of_truth
14) Recommended sync algorithm
A workable pattern:
- Initial full import
- Set up webhook/subscription
- On webhook, enqueue sync
- Use provider incremental sync endpoint
- For each changed item:
- if remote change is newer than local unsynced change, apply remote
- if local change exists, push local update
- Periodically run reconciliation scan
- Refresh expired sync tokens/subscriptions
15) Practical advice
If you’re starting from scratch:
- Start with one provider first (usually Google)
- Sync one-way first, then make it two-way
- Keep recurrence support minimal initially
- Add conflict handling later
- Build excellent logging and observability from day one
You’ll need:
- sync job logs
- provider API request logs
- dead-letter queue
- metrics on sync lag and failure rate
16) If you want the fastest path
If your product doesn’t need to own the sync logic itself, consider:
- a calendar sync middleware/vendor
- integration platforms
- or a specialized sync layer
That can save months of edge-case work.
If you want, I can also give you:
- a provider-specific implementation plan for Google + Microsoft,
- a database schema + sync worker design, or
- a step-by-step sequence diagram for two-way sync.