The offline sync bug that taught me about temporary IDs
Everything synced perfectly in testing. Then one edit made while offline came back as a 404. The bug was in my assumptions, not my API.
MyJournalApp is an offline-first journaling PWA I built to see, up close, how production apps handle things like sync, caching and auth. It was more of a learning project than an innovation. This is the bug from it that taught me the most.
How the offline queue works
When you create, edit or delete an entry, the app tries the API first. If fetch fails with a network error (a TypeError: Failed to fetch), the action isn't lost. It gets saved into an IndexedDB queue instead. Real server errors, like a 400 or a 500, are not queued: they are thrown normally, because retrying them later won't help.
const runOfflineFallback = async () => {
const tempId = `temp-${Date.now()}`
await addOfflineAction({
action: 'CREATE',
entryId: tempId,
payload: { title },
timestamp: new Date().toISOString(),
})
await registerBackgroundSync()
return { id: tempId, title, date: new Date().toISOString().split('T')[0] }
}The function returns immediately with the temporary ID, so the UI updates as if the request had worked. When the device comes back online, the browser's Background Sync API wakes up the service worker, and it replays the queue in order.
Offline writes and background sync went in on 14 June. I tested the obvious flows: create offline, come back online, check the entry is there. Everything passed. Then I tried a sequence that real users do all the time, and it broke.
The 404 that should not exist
Create an entry while offline. It gets an ID like temp-1718782800000. Now, still offline, edit that same entry. The queue now holds two actions, and both point at the temporary ID. Come back online:
- 1The CREATE replays and succeeds. The server generates a real MongoDB ID.
- 2The UPDATE replays and sends
PUT /api/journals/temp-1718782800000. - 3The server has never heard of that ID: 404 Not Found.
Same thing for a DELETE queued after the CREATE. The edit just disappears, and in the UI the entry is stuck pointing at an ID that doesn't exist.
The bug was in my thinking
The API was fine. The bug was my assumption that an ID would stay the same throughout the sync process. I had built the happy path, where you create something and then sync. I hadn't thought through what happens when a temporary identity becomes a permanent one halfway through a queue.
Sometimes the hardest bugs aren't caused by bad code. They're caused by incomplete thinking.
Before touching the code, I wrote the problem down in Notes/PWA_issues.md as a checklist: understand the problem, capture the real ID from the CREATE, update the queued actions, update the UI, then test create offline → edit offline → come online end to end. The checklist covered every place a temporary ID lives: the IndexedDB queue, the list being replayed, and the UI.
The fix: a temp-to-real ID map
After a CREATE succeeds, the service worker reads the real ID from the response, remembers the mapping, and rewrites every pending action that still points at the temporary ID, both in IndexedDB and in the in-memory list it is currently looping over.
// Map to link temporary IDs created offline with database MongoDB IDs
const idMap = new Map()
for (const action of compactedActions) {
let entryId = action.entryId
if (idMap.has(entryId)) entryId = idMap.get(entryId)
if (action.action === 'CREATE') {
const data = await (await fetch('/api/journals', { method: 'POST', /* ... */ })).json()
const tempId = action.entryId
const realId = data.id
idMap.set(tempId, realId)
// Resolve temp IDs in the remaining IndexedDB queue
for (const dbAction of await getOfflineActions()) {
if (dbAction.entryId === tempId) {
dbAction.entryId = realId
await updateOfflineAction(dbAction)
}
}
// ...and in the in-memory list for the current loop
}
// UPDATE and DELETE now use the resolved entryId
await deleteOfflineAction(action.id) // only after the backend accepts it
}Two smaller details matter here. A DELETE for an ID that is still temp-... is skipped entirely, because the server never had it. And when the queue is done, the service worker sends a SYNC_COMPLETE message with the whole ID map to every open tab, so the UI can swap temporary IDs for real ones without a refresh.
Then I tested exactly the scenario that broke: create offline, edit offline, come back online, check that everything lands.
The follow-up: compacting the queue
Fixing IDs exposed a second problem. If you create an entry, edit it three times and then delete it, all offline, the queue holds five actions that cancel each other out. Replaying all five wastes requests, and can even fail, for example a DELETE arriving before its CREATE. So before replaying, the queue gets compacted with a few rules:
- CREATE then DELETE of the same entry: drop both. There is nothing to sync.
- CREATE then UPDATEs: merge the updates into the CREATE payload.
- UPDATE then UPDATE: keep only the merged result.
- UPDATE then DELETE: keep only the DELETE.
if (prior.action === 'CREATE') {
if (action.action === 'UPDATE') {
// Merge payload into the CREATE action
prior.payload = { ...prior.payload, ...action.payload }
discardedActionIds.add(action.id)
} else if (action.action === 'DELETE') {
// CREATE followed by DELETE: discard both
discardedActionIds.add(prior.id)
discardedActionIds.add(action.id)
entryMap.delete(entryId)
}
}Ten edits to one entry now become one request, and the redundant actions are deleted from IndexedDB before the replay starts.
The temp-ID fix shipped as PR #9 and the compaction as PR #10. Once I started looking at the edges, I kept finding more: the same day I merged six more PWA fixes (#11 to #16), for stale-cache lockouts, query parameters breaking cache matches, lazy chunks failing offline, Safari reporting offline errors differently, the service worker not taking control immediately, and duplicate push subscriptions.
What else offline-first taught me
- Service Worker caching strategies that don't lock users into a stale app shell after a deploy.
- Handling React chunk-loading failures while offline with custom Error Boundaries.
- Web Push notifications (VAPID + node-cron) for daily journaling reminders.
- A multi-container Docker setup with persistent database volumes.
Every bug teaches me something new. This one was about state synchronization, temporary identities, and why edge cases deserve as much attention as the happy path.