Skip to content

Conflict resolution on the client

What a client does when the copy it edited is no longer the copy on the server: detect the stale write with a version, then retry, merge, ask the user, or accept a winner on purpose.

On this page

What it is

A conflict on the client is a write built on a copy the server no longer holds. Two people open the same record, each edits their copy, and each saves. Without a check, the second save to arrive replaces the first, the first person isn't told, and which edit survives depends on whose write reached the server last, which in turn depends on client, server and network speed and on how long each person took to edit. This is the lost update, and because the winner changes from one run to the next it's a hard bug to reproduce.

The fix has two halves. The first is detection: the client sends the version of the copy it read along with the write, and the server refuses a write whose version is stale. In HTTP that's a conditional request, an If-Match header carrying the ETag from the earlier read (or If-Unmodified-Since with its date), and the refusal is 412 Precondition Failed. The first client to save succeeds; later saves built on the old version are rejected. A sync library can do the same with a revision field: PouchDB 9 rejects a put() whose _rev isn't the current one with a 409 conflict error, including when live replication pulled someone else's change in while the person was still editing.

The second half is what the client does with the refusal, and this is where a design has to make a choice. The options, roughly from cheapest to most involved: refetch and reapply a change that doesn't depend on what was read; merge the two copies when they touched different fields; show the person both versions and let them decide; or decide up front that one side wins and skip the rest. Which one fits depends on what the data is and how much an edit is worth.

ts
type Result =
  | { kind: 'saved'; etag: string }
  | { kind: 'conflict'; mine: Doc; theirs: Doc; etag: string };

// base: the copy we read, before edits. Needed to tell who changed what.
async function save(base: Doc, mine: Doc, etag: string, tries = 3): Promise<Result> {
  const res = await fetch(`/docs/${mine.id}`, {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json', 'If-Match': etag },
    body: JSON.stringify(mine),
  });
  if (res.status !== 412) {
    if (!res.ok) throw new Error('save failed');
    return { kind: 'saved', etag: res.headers.get('ETag') ?? '' };
  }
  // The server's copy no longer matches our tag: changed, or gone.
  const fresh = await fetch(`/docs/${mine.id}`);
  if (fresh.status === 404) throw new Error('record was deleted');
  const theirs: Doc = await fresh.json();
  const freshTag = fresh.headers.get('ETag') ?? '';
  const merged = mergeByField(base, mine, theirs); // assumed helper: null when both edited one field
  if (merged && tries > 0) return save(theirs, merged, freshTag, tries - 1);
  return { kind: 'conflict', mine, theirs, etag: freshTag };
}

When to use it

Send a version with each write that replaces data someone else could have changed: a shared record, a settings page several admins open, anything edited after a spell offline. A version check costs one header and turns a silent overwrite into an error the client can act on. Prefer an ETag over a last-modified date as the validator: a date is a hard thing to make unique per version, while an ETag is an opaque string the server mints for exactly that purpose, often from a hash of the content.

Retry on top of the fresh copy when the change is a delta, a change that doesn't depend on the version it was written against: add one to a count, flip a flag, append an item. The sync guides call this an upsert: read the current document, apply the function that expresses the change, write, and repeat on a conflict. Our advice: express as many user actions as deltas as you can, because a delta is the simplest kind of edit for the client to resolve with no help from the person.

Merge by field when two edits touched different parts of a record. This needs three copies: the base you read, your edited copy and the server's. Comparing yours with theirs isn't enough, because a field that differs could have been changed by either side; comparing each against the base tells you who changed what. Keep the base alongside the form state from the moment the record loads.

Ask the person when both sides changed the same field. Show both versions, or a diff, and let them pick what to keep. Whatever you do, their typing stays on screen until they choose: a conflict that comes back as a plain 'save failed' and an empty form has lost the edit as surely as an overwrite would have. When the data is shared across devices that go offline, expect conflicts to surface later too, not just at save time: CouchDB-style replication picks a deterministic winner so all replicas agree, and lists the losing revisions on the document when asked, so the app can fetch them and resolve the conflict.

When not to

Skip detection when one person on one device owns the data and nothing else writes it: a local draft, a per-device preference, a theme toggle. Last write wins is the right answer there, and a version check adds an error path and a refetch-and-retry branch with no second writer to catch. Say so in the round: choosing the simple option on purpose, with the reason, reads better than adding machinery to data with a single writer.

Skip merging when each change can be written as a new record. If a change is its own document, a ledger entry with its own id rather than an update to a balance, two writers don't touch the same document and the current value is a sum over the entries. This removes the conflict instead of resolving it, at the price of a read that aggregates.

Don't build field merging for live collaborative text. Two people typing in one paragraph are editing the same field at the same time, so a per-save diff is the wrong grain; that problem has its own data structures, covered in Operational transforms and CRDTs. And when a record is small and rarely contended, a 412 that reloads the fresh copy and asks the person to redo a one-field edit is acceptable; a three-way merge is worth writing once the edit is long enough that losing it hurts.

Compared

ApproachHow it worksRight whenWhat it costs

Last write wins, no check

The latest save replaces the record

One owner, one device, or an edit that's cheap to lose

Silent lost updates once a second writer appears

Version on the write

If-Match with the ETag, or a _rev; stale writes get 412 or 409

Anything someone else might edit

You must handle the rejection, not just show an error

Retry a delta

Refetch, reapply a change that doesn't depend on the old copy, resend

Counters, flags, appends

Needs a retry bound; not for free-text edits

Three-way field merge

Compare base, mine and theirs; take each side's changed fields

Forms with many independent fields, where two edits can land on different ones

Keeping the base copy; a rule for the same field edited twice

Ask the person

Show both versions or a diff, let them pick

The same field changed on both sides, and the edit is worth keeping

A UI to build and a decision the person must make

New record per change

Each change is a new document; the value is derived

Ledgers, logs, counts that sum

A read that aggregates, and no in-place edit

Deterministic winner

Replication picks the same winner everywhere, keeps the loser

Offline replicas that must converge now and reconcile later

The app must look for conflicts and resolve them

In a picture

Server: ETag aClient A reads aClient B reads a

Step 1 of 4

Both read version a

Two clients load the same record. The response carries ETag: "a", and each client keeps that tag with the copy it is about to edit.

How to say it in an interview

The common mistake

Quiz

Two clients read a record with ETag "a". Client A saves with If-Match: "a" and gets ETag "b" back. Client B then saves with If-Match: "a". What happens?
Which change can the client safely reapply on top of a fresh copy after a conflict, with no help from the person?
For a field-level merge after a 412, why keep the copy you originally read, not just your edited copy and the server's?
Which of these is the best case for skipping version checks and letting the last write win?

Related

Sources

  1. MDN: HTTP conditional requests
  2. PouchDB guides: Conflicts (PouchDB 9.0.0)
Sign in to report a mistake