Background Mail Sync (Stale-While-Revalidate)
- Deciders: Julian Baume
- Date: 2026-04-11
Status
Accepted
Context
The GET /api/threads/:inboxId endpoint synchronously calls the Java middleware's mail?action=sync on every request. This checks IMAP for changes and, if any are found, fetches all threads via mail?action=threadedAll and reimports them into PostgreSQL.
Production measurements showed this adds 300-700ms to every request in steady state (cached App Suite session), and up to ~3s when the session needs to be recreated (after Keycloak token expiry). This latency is paid even when the mailbox hasn't changed — the sync call itself is the bottleneck, not the DB queries (~10-50ms).
For shared/public folders with low mail volume (e.g., <100 mails, unchanged for months), users experience a noticeable delay every time they navigate to the folder, with no perceptible benefit.
Decision
Decouple the middleware sync from the HTTP response using a stale-while-revalidate pattern:
Always return DB data immediately. The handler queries PostgreSQL and responds without waiting for the middleware sync.
Trigger sync in the background. If the last sync for this inbox was more than
SYNC_INTERVALseconds ago (default: 30s), a background sync is started. The sync promise is tracked per inbox in an in-memory map.Signal sync state via response header. The response includes
X-Sync-State: syncing | idleso the client knows whether fresher data may be incoming.Client re-fetches with
?awaitSync=true. When the frontend seesX-Sync-State: syncing, it fires a follow-up request that blocks until the background sync completes, then updates the UI with the result.
Key design choices
In-memory state, not DB: The sync state map (lastSyncAt, in-progress promise) lives in process memory. A DB-based approach would add query overhead to the hot path and require a migration. After a process restart, a fresh sync is desirable anyway.
Per-inbox, not per-user: The sync token and imported threads are shared across all users of an inbox. One user's sync benefits all subsequent requests from any user.
Header, not response body: Using X-Sync-State as a header avoids changing the response schema (stays Thread[]), preserving backward compatibility.
No special-casing for first request: Even the very first request (empty DB) returns immediately with [] and X-Sync-State: syncing. The client's awaitSync follow-up fills in the data. This keeps the handler logic uniform.
Consequences
Positive
- Thread list loads in ~10-50ms (DB query time) instead of 300-3000ms
- Users see DB-level changes (status updates, assignments, comments) instantly without waiting for IMAP sync
- Repeated navigations within the sync interval skip the middleware call entirely
- No database migration required
Negative
- New IMAP mail appears with a delay of up to
SYNC_INTERVALseconds (default 30s) plus the sync duration - First visit to a folder after process restart shows stale (or empty) data briefly before the
awaitSyncfollow-up completes - The frontend makes two requests when sync is pending (immediate + awaitSync), though the first is fast
Risks
- If the background sync fails silently (e.g., persistent session issues), users may see stale data indefinitely until the next successful sync. Error logging mitigates this, but no automatic retry beyond the next request is implemented.
- The
awaitSyncfollow-up is fire-and-forget in the frontend — if the user navigates away before it completes, the result is discarded. This is intentional (avoids updating the wrong folder's view) but means rapid folder switching may never complete a sync.
Alternatives Considered
Frontend-only throttle: Caching in the Pinia store and skipping API calls for recently-fetched folders. Rejected because DB-level changes from other users (status updates, new comments) would also be delayed, not just IMAP mail.
Sync TTL (skip sync, don't background it): Simply not calling the middleware if synced recently and returning DB data. Simpler but means the client has no way to get fresh IMAP data on demand — there's no follow-up mechanism. The stale-while-revalidate approach gives the client control over when to wait for fresh data.
Server-Sent Events / WebSocket push: Notifying the client when a background sync completes, instead of the client polling with awaitSync. More efficient but significantly more complex to implement and would require a new transport mechanism for this single use case.

