d.deepak chauhanFULL STACK DEVELOPERLet’s talk
ONE PORTFOLIO. THREE PERSPECTIVES.

INTEGRATIONS / BY DEEPAK CHAUHAN

Designing reliable OAuth Calendar and Mailbox sync boundaries

By Deepak Chauhan7 min read

Integrating Google Calendar, Microsoft Outlook Calendar, Gmail, and Outlook mailboxes surfaces two classic production failure modes: concurrent token refreshes invalidating rotating credentials, and duplicate records created by overlapping webhooks and scheduled sync jobs.

Serialize OAuth token refreshes per connection

When a user loads a multi-panel dashboard or two BullMQ sync jobs fire simultaneously near token expiration, both workers read the same expired token and send parallel refresh requests. Providers that rotate refresh tokens on each exchange invalidate the first response as soon as the second arrives—leaving the mailbox disconnected.

Guard token refresh behind a short-lived Redis lock scoped to connectionId. Once a worker acquires the lock, re-read the persisted token row before calling Google or Microsoft's token endpoint; if the preceding worker already refreshed and persisted a new expiry timestamp, return the fresh token immediately.

Double-checked single-flight OAuth refresh pattern

// Refresh only when near expiry and single-flight per connection
if (expiresAt - Date.now() < 60_000) {
  return await withRedisLock(`oauth:refresh:${connectionId}`, 15_000, async () => {
    const latest = await getConnectionTokens(connectionId);
    if (latest.expiresAt - Date.now() >= 60_000) {
      return latest;
    }
    return await refreshAndPersistToken(connectionId, latest.refreshToken);
  });
}

Use incremental sync cursors with safe 410 Gone fallback

Polling entire calendars or inboxes wastes quota and stalls background queues. Persist each provider's incremental cursor—Google Calendar's nextSyncToken, Gmail's historyId, or Microsoft Graph's @odata.deltaLink—alongside the connection state.

Provider cursors expire periodically (for example, after prolonged inactivity or permission changes), returning HTTP 410 Gone. Catch 410 cleanly, clear the stored cursor inside a transaction, run a bounded lookback sync (e.g., last 30 days), and save the newly issued cursor.

  • Encrypt access and refresh tokens at rest before writing them to PostgreSQL.
  • Scope OAuth permissions strictly to required calendar/mail read-write scopes.
  • Advance the stored cursor only after all fetched page items commit successfully.

Keep incoming and outgoing mailbox logging idempotent

Treat both push webhook notifications and periodic polling sweeps as at-least-once triggers. Key synced calendar events and logged emails on a composite unique constraint (connection_id, provider_message_id) rather than checking existence in application memory.

Upserting on that unique key ensures overlapping backfill jobs update modified event times, attendee statuses, or email thread links without duplicating CRM activity timeline entries.

Composite unique upsert for calendar and email activity logs

INSERT INTO synced_communications (
  connection_id, provider_message_id, thread_id, direction, subject, occurred_at
)
VALUES ($1, $2, $3, $4, $5, $6)
ON CONFLICT (connection_id, provider_message_id)
DO UPDATE SET
  subject = EXCLUDED.subject,
  occurred_at = EXCLUDED.occurred_at,
  updated_at = NOW();