Why edits get lost
A typical autosave waits for a pause in typing, then sends the whole document:
let timer;
editor.addEventListener("input", () => {
clearTimeout(timer);
timer = setTimeout(() => {
fetch(`/api/notes/${noteId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: editor.value }),
});
}, 800);
});
The debounce sends fewer saves, but it does not put them in order. If the first save takes two seconds on a weak connection and the second takes 200 ms, the server can store the newer text first and the older text last. The editor still shows the newest text, so nothing looks wrong until a reload.
The same race comes in three shapes:
- Two saves from one tab arrive out of order, and the older one wins.
- A read that started before an optimistic update answers after it, and a checkbox or a like count flips back.
- Two tabs or two people save the same record, and the second save silently replaces the first: the "lost update" problem that RFC 6585 describes.
In each case the last write to arrive wins, whatever data it was based on. Nothing throws, so an error tracker records nothing.
Fix 1: send one save at a time
Keep one save in flight per document. While it runs, remember only the newest text, and send it when the current save answers. The server then gets the saves in the order the user made them, and any number of edits during a slow save cost one more request.
// One save in flight. A queued save is skipped when a newer one
// is waiting, so the newest text is always the last one sent.
function serialSaver(send) {
let queue = Promise.resolve();
let latest = 0;
return function save(text) {
const n = ++latest;
const run = queue.then(() => (n === latest ? send(text) : undefined));
queue = run.catch(() => {}); // a failed save does not block the next one
return run;
};
}
const save = serialSaver(async (text) => {
const res = await fetch(`/api/notes/${noteId}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: text }),
});
if (!res.ok) throw new Error(`Save failed: ${res.status}`);
});
// in the debounced handler:
save(editor.value).catch(showNotSaved);
When a save fails, say so next to the editor and offer a retry. Aborting the older request is no fix for writes: it may already be on the server, which can still apply it after the newer one.
Fix 2: let the server drop older saves
Even with a queue, a retry or a second code path can deliver saves out of order, so number each save and let the server keep only the newest. Start from the number the server last stored; a count that restarts at zero after a reload has its saves dropped.
let seq = note.seq; // the number the server last stored, loaded with the note
function saveWithSeq(text) {
seq += 1;
return fetch(`/api/notes/${note.id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ body: text, seq }),
});
}
On the server, check and write in one statement: UPDATE notes SET body = $1, seq = $2 WHERE id = $3 AND seq < $2. If no row changed, a newer save is already stored. A separate read, then a write, brings the race back.
This orders one tab's saves. Two tabs count on their own, their numbers collide, and one tab's edit vanishes without an error; two writers need the version check below.
Fix 3: ETag, If-Match and 412 for two tabs
With two writers, the server has to know which version each edit started from. HTTP has this built in: the server sends the record's version in the ETag header, the browser sends it back in If-Match with the save, and if the record changed in between, the server answers 412 Precondition Failed instead of saving. RFC 9110 says the server must not perform the request when that condition is false.
let etag; // the version this tab's edits are based on
async function loadNote(id) {
const res = await fetch(`/api/notes/${id}`);
etag = res.headers.get("ETag"); // a strong tag, such as "42"
return res.json();
}
async function saveNote(id, changes) {
const res = await fetch(`/api/notes/${id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json", "If-Match": etag },
body: JSON.stringify(changes),
});
if (res.status === 412) return "conflict"; // changed since this tab loaded it
if (!res.ok) throw new Error(`Save failed: ${res.status}`);
etag = res.headers.get("ETag"); // the next save builds on this version
return "saved";
}
On the server, compare and write in one statement: UPDATE notes SET body = $1, version = version + 1 WHERE id = $2 AND version = $3. If no row changed, answer 412; otherwise answer with the new version as the ETag, like the 204 in the PATCH example of RFC 5789. Answering 428 Precondition Required to a save with no If-Match keeps old clients from skipping the check.
- Use a strong tag, such as the version number. MDN notes that a weak tag, with a
W/prefix, never matches in If-Match, so every save would get a 412. - Send autosaves through the queue from Fix 1. Two saves in flight from one tab carry the same ETag, so whichever arrives second gets a 412 against the tab's own save.
- If the API is on another origin, its CORS headers must allow If-Match (Access-Control-Allow-Headers) and expose ETag (Access-Control-Expose-Headers). Without the second,
res.headers.get("ETag")returns null in the browser.
Fix 4: cancel refetches before an optimistic update
A value that flips back after a click is often a read that started before the click and answered after it, writing the old value over the optimistic one. In TanStack Query, cancel the queries for that key in onMutate, as its optimistic updates guide shows; the QueryClient reference explains that a refetch resolving later would overwrite the optimistic update.
const queryClient = useQueryClient();
const toggleTodo = useMutation({
mutationKey: ["todos"],
mutationFn: updateTodo,
onMutate: async (todo) => {
// a refetch already in flight would land after this and put the old value back
await queryClient.cancelQueries({ queryKey: ["todos"] });
const previous = queryClient.getQueryData(["todos"]);
queryClient.setQueryData(["todos"], (old) =>
old?.map((t) => (t.id === todo.id ? todo : t)),
);
return { previous };
},
onError: (err, todo, onMutateResult) => {
queryClient.setQueryData(["todos"], onMutateResult?.previous);
},
onSettled: () => {
// refetch once, when no other change to the list is still pending
if (queryClient.isMutating({ mutationKey: ["todos"] }) === 1) {
return queryClient.invalidateQueries({ queryKey: ["todos"] });
}
},
});
If the save fails, onError puts back the snapshot taken in onMutate. The isMutating check covers quick repeated clicks: without it, the first mutation's refetch can answer before the second change is saved and flip the value back. TkDodo, one of the TanStack maintainers, explains this case in Concurrent Optimistic Updates in React Query. With SWR, RTK Query or your own store the rule is the same: a read that started before a change must not write after it.
Fix 5: show the conflict instead of overwriting
When a save comes back 412, do not resend it with the new ETag on your own: that is the same silent overwrite. Keep the user's text, load the current version and let them choose:
- Show both versions, with a line such as "This note changed in another tab. Your text is below."
- Offer to keep theirs (a save with the new ETag, now on purpose) or to take the other version.
- In a form, apply the fields only one side changed and ask only about fields both changed.
For one person in two tabs, a BroadcastChannel can tell the other tabs that a save landed, so they can reload before the user edits old text.
Where GenClass fits
GenClass's runtime reports the browser side of these races. When a response is about to overwrite newer data, undo a local change the server has not confirmed yet, or replace text typed after the request started, it asks its on-device model, and a stale or conflict diagnosis prints one console line with the evidence. In observe, its default mode, it never holds, delays or changes a request, a response or a state write. It finds React state, Redux stores set up for Redux DevTools and Zustand stores with devtools (in production only with enabled: true) on its own, not the TanStack Query, SWR or Apollo caches; other state has to be registered. Scored offline on real apps kept out of its training, the model reported 30% of stale overwrites with the right diagnosis, with false detections held to at most 2% of clean decisions (benchmarks); conflict has no published rate.
On your development build, the MCP server gives your coding agent a stale-write finding when a response put older data over a field that a later request or the user had written. While your agent or a test repeats your steps, genclass_explore delivers the responses in other orders and reports a race when the page text, a form value or the number of PUT, PATCH or DELETE requests ends differently from the in-order run; genclass_replay delivers that order again, before and after your fix. Explore does not hold failed responses, so rollbacks are not reordered, and a value that flips back and is put right later is listed, not reported as a race. A correct save queue like Fix 1's can show up as a race, since it sends fewer PUTs when answers are slow (3 of 3 sessions on GenClass's own test page): check what the server kept before you change code.
Neither one sees which save your server applied last, or a save from another tab: Fix 2 and Fix 3 cover those. Next step: set up the MCP server and explore your editor page. More on editors and dashboards: GenClass for SaaS apps.
Questions
Does debouncing autosave stop lost edits?
No. It sends fewer saves, but a slow save can still reach the server after a newer one, so send one save at a time or have the server drop older saves.
What is the lost update problem?
Two clients load the same record, both change it, and the second save silently replaces the first. A save with If-Match turns that into a 412 response the app can show as a conflict.
Why does my checkbox flip back after I click it?
Often a refetch or an earlier response that started before the click lands after it with the old value. Cancel reads in flight before the optimistic update, and refetch after the last change settles.
How do I roll back an optimistic update?
Keep a copy of the data from before the optimistic write and put it back if the save fails; in TanStack Query, return it from onMutate and restore it in onError. Then refetch once no other change is pending.
Is last write wins ever fine?
Yes, for data one person edits in one tab, as long as "last" means the newest edit, not the last request to arrive. A sequence number lets the server tell the two apart.
Related: race conditions in JavaScript, out-of-order search responses and race conditions in React data fetching.