Full answer
Start with the product rules: which data must work offline, how long, how many devices edit the same data, and what conflicts are acceptable.
Design:
- Local source of truth: the UI reads from local state backed by IndexedDB (not
localStorage, which is small and synchronous). Writes update local state immediately (optimistic), so the app feels instant. - Operations, not state: each change becomes
{ opId, type, entityId, payload, baseVersion, createdAt }. Operations are appended to a persistent queue. Collapse redundant operations when safe (several edits of one field into the last one). - Sync loop: when the app starts, comes back online (
onlineevent, though it is only a hint), or the user retries, send operations in order. Keep ordering per entity, and allow parallel requests for different entities if the server supports it. Only one sync loop runs at a time. - Idempotency: the client sends
opId(an idempotency key), and the server stores processed ids, so a retry after a timeout does not apply a change twice. This is the most important server contract. - Failure handling: network errors and 5xx responses are retried with exponential backoff and jitter. A 4xx validation error is permanent: remove the operation, revert the optimistic change, and tell the user. Authentication errors pause the queue until sign-in.
- Conflicts: the server compares
baseVersionwith the current version. Options are last-write-wins (simple, can lose edits), field-level merge, reject and ask the user, or CRDTs for collaborative text. Choose by business value. - Pull side: after pushing, fetch changes since a cursor and merge them into local state. Server changes win for fields without pending local operations. Rebase pending operations on top of new data.
- Storage limits and schema: version the local database, handle migrations, cap the queue and tell the user when it is full, and clear data on logout.
- Visibility: show states such as "saved on this device", "syncing", "offline", and "needs attention", and let users retry or discard.
- Multi-tab: use
BroadcastChannelor a lock (Web Locks API) so only one tab syncs. - Service worker and Background Sync can send queued data after the page closes where supported, but must not be the only path.
- Testing: simulate offline, partial failure, duplicate delivery, and reordering.
Trade-offs: simple last-write-wins is easy but loses data, and richer merges cost design time, so choose per entity.
function createServer() {
const processed = new Map();
const docs = new Map([['note-1', { text: 'start', version: 1 }]]);
let online = false;
let dropReply = false;
return {
docs,
setOnline: (value) => (online = value),
dropNextReply: () => (dropReply = true),
async handle(op) {
if (!online) throw new Error('network');
if (processed.has(op.opId)) return processed.get(op.opId);
let response;
const doc = docs.get(op.entityId);
if (!op.payload.text) response = { status: 422 };
else if (doc.version !== op.baseVersion) response = { status: 409, version: doc.version };
else {
docs.set(op.entityId, { text: op.payload.text, version: doc.version + 1 });
response = { status: 200, version: doc.version + 1 };
}
processed.set(op.opId, response);
if (dropReply) {
dropReply = false;
throw new Error('timeout after the server applied the change');
}
return response;
},
};
}
function createClient(server) {
const local = new Map([['note-1', { text: 'start', version: 1 }]]);
const queue = [];
const log = [];
let n = 0;
let syncing = false;
return {
local,
log,
queue,
edit(entityId, text) {
const doc = local.get(entityId);
queue.push({ opId: `op-${++n}`, entityId, payload: { text }, baseVersion: doc.version, backup: { ...doc } });
local.set(entityId, { text, version: doc.version });
},
async sync() {
if (syncing) return;
syncing = true;
try {
while (queue.length) {
const op = queue[0];
let result;
try {
result = await server.handle(op);
} catch (error) {
log.push(`${op.opId}: ${error.message}, kept for retry`);
return;
}
queue.shift();
if (result.status === 200) {
local.set(op.entityId, { text: op.payload.text, version: result.version });
queue.filter((next) => next.entityId === op.entityId).forEach((next) => (next.baseVersion = result.version));
log.push(`${op.opId}: applied, version ${result.version}`);
} else {
local.set(op.entityId, op.backup);
log.push(`${op.opId}: rejected with ${result.status}, local change reverted`);
}
}
} finally {
syncing = false;
}
},
};
}
(async () => {
const server = createServer();
const client = createClient(server);
client.edit('note-1', 'offline edit one');
client.edit('note-1', 'offline edit two');
console.log('offline, UI shows:', client.local.get('note-1').text, '| queued:', client.queue.length);
await client.sync();
console.log('still offline:', client.log.at(-1), '| queued:', client.queue.length);
server.setOnline(true);
server.dropNextReply();
await client.sync();
console.log('reply lost:', client.log.at(-1));
await client.sync();
console.log('retry is idempotent:', client.log.slice(-2), '| server doc:', JSON.stringify(server.docs.get('note-1')));
client.edit('note-1', '');
await client.sync();
console.log('validation error:', client.log.at(-1), '| UI shows:', client.local.get('note-1').text);
server.docs.set('note-1', { text: 'edited elsewhere', version: 9 });
client.edit('note-1', 'my late edit');
await client.sync();
console.log('conflict:', client.log.at(-1), '| UI shows:', client.local.get('note-1').text);
console.log('server doc:', JSON.stringify(server.docs.get('note-1')), '| queue empty:', client.queue.length === 0);
})();Run with Node.js v24.22.1 as js-188.js; two runs gave identical output. Output: offline, UI shows: offline edit two | queued: 2 still offline: op-1: network, kept for retry | queued: 2 reply lost: op-1: timeout after the server applied the change, kept for retry retry is idempotent: [ 'op-1: applied, version 2', 'op-2: applied, version 3' ] | server doc: {"text":"offline edit two","version":3} validation error: op-3: rejected with 422, local change reverted | UI shows: offline edit two conflict: op-4: rejected with 409, local change reverted | UI shows: offline edit two server doc: {"text":"edited elsewhere","version":9} | queue empty: true
Key points
- Optimistic local writes backed by IndexedDB; the queue stores operations with ids.
- Replay in order, one loop at a time; the server dedupes by operation id.
- Retry network and 5xx errors with backoff; remove and revert permanent failures.
- Detect conflicts with versions and choose a clear resolution policy.
- Show sync status; handle multiple tabs, migrations, and logout.
Common mistakes
- Using localStorage as the main offline database.
- Retrying operations without an idempotency key, which applies them twice.
- Replaying operations out of order for the same entity.
- Hiding sync state from the user.
Follow-ups
- How would you merge text edits from two devices?
- What does the pull side of sync look like?
- How would you handle several tabs?
Tips
- Describe operations plus idempotency keys as the core.
- Choose a conflict policy and justify it.
- Say how the user sees pending, failed, and synced states.