Local-first architecture with sync queues
Quick Guide: Reads and writes go to a local database first and the network catches up afterwards. IndexedDB is the store — reached through a wrapper such as Dexie (reactive queries, larger) or idb (thin, ~1.2KB) — and every syncable record carries
_syncStatus,_lastModifiedand_localVersionso the queue knows what is outstanding. Deletes are tombstones, never removals, or a delayed sync resurrects them. The Background Sync API is Chromium-only, so anonlinelistener is the mechanism and background sync the optimisation.
Detailed Resources:
<critical_requirements>
Treat the local database as authoritative. Every read comes from it and every write lands there before anything is sent, which is what makes the UI answer instantly whatever the connection is doing.
Give every syncable record _syncStatus, _lastModified and _localVersion. Without them
there is no way to ask what is outstanding, and no way to tell a conflict from a fresh write.
Delete by writing a _deletedAt tombstone. A removed row has nothing left to sync, so the next
pull brings the record back.
Queue every mutation and drain the queue on reconnect, with exponential backoff and jitter. A transient 502 is otherwise a permanently lost write, and synchronised retries from many clients are what turn a brief outage into a long one.
Keep an IndexedDB transaction free of any other await. The transaction closes as soon as
control returns to the event loop with no request pending, so an awaited fetch mid-transaction
fails with TRANSACTION_INACTIVE_ERR. Fetch first, then open the transaction.
</critical_requirements>
Auto-detection: IndexedDB, indexedDB.open, IDBDatabase, IDBObjectStore, openDB, DBSchema, Dexie, useLiveQuery, dexie-react-hooks, idb-keyval, sync queue, tombstone, _syncStatus, _lastModified, last-write-wins, version vector, offline-first, local-first, navigator.onLine, navigator.storage.persist, BroadcastChannel, QuotaExceededError
Applies to:
Handled elsewhere:
The network is an enhancement. Local storage is the database, and the server is a peer it reconciles with — which inverts the usual arrangement, where local storage is a cache of the truth.
Two things follow. Writes never block on a request, so the UI responds at disk speed rather than at network speed. And every write becomes a claim that may be contested, which is why sync metadata is foundational rather than an add-on: a record with no version is a record no merge can reason about.
User action
│
Local database ←── the single source of truth
│
UI updates immediately
│
Sync queue (background)
│
Server, when reachable
│
Conflict resolution, if the record moved on both sides
│
Local database updated
The user's remaining job is trust: they need to see that a change is saved, that it is queued, and that it eventually landed. Sync status is a product surface, not a debugging aid.
</philosophy>Every other pattern reads these fields. Business data and sync metadata stay separate, with the metadata prefixed so a merge can skip it wholesale.
interface SyncableEntity {
id: string;
_syncStatus: "synced" | "pending" | "conflicted";
_lastModified: number;
_serverTimestamp?: number;
_localVersion: string;
_serverVersion?: string;
_deletedAt?: number; // tombstone
}
Full code: examples/core.md
One access point for a collection, so no caller has to remember that a write is two operations. Reads filter tombstones; writes stamp metadata, save locally, then enqueue.
interface DataRepository<T extends SyncableEntity> {
get(id: string): Promise<T | null>; // null for a tombstone
getAll(): Promise<T[]>;
save(item: T): Promise<void>; // local write, then enqueue
delete(id: string): Promise<void>; // tombstone, then enqueue
getPendingCount(): Promise<number>;
}
Full code: examples/core.md
Exponential delay bounded by a ceiling, plus jitter so reconnecting clients do not arrive together.
const INITIAL_BACKOFF_MS = 1000;
const MAX_BACKOFF_MS = 30_000;
const JITTER_FACTOR = 0.5;
function calculateBackoff(attempt: number): number {
const delay = Math.min(INITIAL_BACKOFF_MS * 2 ** attempt, MAX_BACKOFF_MS);
const jitter = delay * JITTER_FACTOR * (Math.random() * 2 - 1);
return Math.floor(delay + jitter);
}
Full code: examples/core.md — retry limits, ordering by timestamp, dead-letter handling
navigator.onLine reports whether a network interface exists, which is true behind a captive
portal and on a router with no upstream. Confirm with a request.
async function checkConnectivity(): Promise<boolean> {
if (!navigator.onLine) return false; // cheap negative, trustworthy
try {
const response = await fetch("/api/health", {
method: "HEAD",
cache: "no-store",
});
return response.ok;
} catch {
return false;
}
}
Full code: examples/core.md — latency sampling and a "slow" state
Capture the previous value before writing and hand back the undo, so the caller's error path is one call rather than a reconstruction.
async function applyOptimistically<T>(id: string, next: T) {
const previous = (await localDb.get(id)) ?? null;
await localDb.put(next);
return async function rollback() {
if (previous) await localDb.put(previous);
else await localDb.delete(id);
};
}
Full code: examples/core.md
Return where the data came from alongside the data, so the UI can say "showing saved data" instead of silently presenting something stale as current.
interface FetchResult<T> {
data: T;
source: "network" | "cache";
timestamp: number;
}
// try network with a timeout, cache the success, fall back to cache on any failure
const response = await fetch(url, { signal: AbortSignal.timeout(TIMEOUT_MS) });
Full code: examples/core.md
Three strategies, in increasing cost. Pick by what the field means, not by what is easiest.
Where neither side can be discarded, surface the conflict and let the user choose: examples/sync.md Pattern 19.
</patterns><red_flags>
Breaks at runtime:
await fetch(...) or await new Promise(setTimeout) inside an IndexedDB transaction — the
transaction has already closed and the next operation throws TRANSACTION_INACTIVE_ERR — do the
async work first, then open a short transaction_deletedAt
and sweep tombstones once they are confirmed syncedQuotaExceededError surfaces as a failed save with no
warning — check navigator.storage.estimate() and evict before writingSurprising behaviour:
navigator.onLine === true means an interface exists, not that anything is reachablenavigator.storage.persist() helps and an installed app helps morenavigator.storage.estimate() needs a secure context and answers { usage: 0, quota: 0 }
otherwiseonline listener has to carry the load everywhere else[userId+completed] against
[userId, 1]useLiveQuery returns undefined while loading, not null, so a === undefined check
is the loading stateBroadcastChannel is how they agree
(examples/indexeddb.md Pattern 15)</red_flags>
npx skills add agents-inc/web-pwa-offline-first下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer