Engineering
Continuous Google Calendar Sync: Zero-Latency Architecture
Deep dive into our event-driven bidirectional sync architecture, handling Google OAuth token renewals, rate limits, and push notification webhooks.
Taras Shevchenko
Staff Infrastructure Engineer
Published on 2026-09-20
6 min read

Key Takeaways
Bidirectional sync without idempotency keys is a recipe for infinite event loops and duplicate calendar clutter.
Google Workspace push notifications require short-lived channels renewed via serverless cron routines.
Decoupling the client mutation from the calendar API call via an asynchronous event bus ensures sub-100ms response times for users.
1. The Two-Way Calendar Conundrum
Synchronizing business applications with Google Calendar sounds trivial until you handle:
1. Google API rate limits (quota errors on bulk team updates).
2. Expired OAuth refresh tokens during background sync tasks.
3. Event loops: Sferafy writes an event to Google $\rightarrow$ Google sends a webhook to Sferafy $\rightarrow$ Sferafy interprets it as a user modification $\rightarrow$ Sferafy rewrites to Google.
Without rigorous event design, users quickly find their work calendars polluted with duplicate OOO entries.
2. The Sferafy Sync State Machine & Idempotency Key
To achieve 100% deterministic sync, every calendar modification in Sferafy generates a deterministic hash:
`hash(company_id + user_id + request_id + date_range + status)`.
When Google's notification webhook fires, our ingress handler compares the incoming Google event ID with our stored `google_event_id` mapping table. If the version tag matches our latest outbound mutation, the webhook is acknowledged with a 200 OK and discarded immediately.
src/lib/calendar/sync-engine.ts
export async function handleGoogleWebhook(req: Request) {
const channelToken = req.headers.get("x-goog-channel-token");
const resourceState = req.headers.get("x-goog-resource-state");
// 1. Verify cryptographic channel authenticity
if (!verifyChannelToken(channelToken)) {
return new Response("Unauthorized", { status: 401 });
}
// 2. Ignore initial sync sync-token ping
if (resourceState === "sync") {
return new Response("OK", { status: 200 });
}
// 3. Dispatch to idempotent processing queue
await eventQueue.push({ type: "CALENDAR_WEBHOOK", timestamp: Date.now() });
return new Response("Queued", { status: 202 });
}3. UI Optimism & Background Dispatch
When an employee submits an urgent leave request or remote shift, their local view updates in zero milliseconds via optimistic React state.
The background worker handles Google API communication in a resilient queue with exponential backoff. Even if Google's API experiences temporary degradation, the employee's internal schedule is never blocked.
Tags:Google CalendarEvent ArchitectureWebhooksTypeScript