← Back to Backend, page 1

backend-0004 · Medium mid

What is the difference between PUT and PATCH, how does JSON Merge Patch work, and how do ETag and If-Match protect against lost updates?

PUT sends a full replacement, so missing fields are removed, and it is idempotent. PATCH sends only the changes. JSON Merge Patch (RFC 7396) is a simple format: send a partial object, fields set to null are deleted, objects merge recursively, arrays are replaced. To avoid lost updates the server returns an ETag (a version of the representation) and the client sends If-Match with it on the write. If it no longer matches, the server answers 412 Precondition Failed.

Full answer

PUT versus PATCH

  • PUT /students/1 with a body means: make the resource exactly this. A field you leave out is gone. Same input, same state: idempotent.
  • PATCH /students/1 with a partial body means: apply these changes. Smaller requests, and clients do not need to know the whole resource.

Patch formats

  • JSON Merge Patch (application/merge-patch+json): easy. The body looks like the resource. null removes a field. Arrays are replaced as a whole, and you cannot set a value to null on purpose.
  • JSON Patch (application/json-patch+json, RFC 6902): a list of operations such as { op: "replace", path: "/name", value: "x" }. More precise (array items, test operations) but more complex.

Lost updates

  • Two clients read version A. Client 1 writes, then client 2 writes from stale data and silently overwrites the first change.
  • Fix: the server sends ETag: "v7" on GET. The client sends If-Match: "v7" on PUT or PATCH. If the current ETag differs, answer 412 and let the client re-read and merge. Use If-None-Match: * to create only if absent. A missing If-Match on a write can be answered with 428 Precondition Required.
javascript
const crypto = require('node:crypto');

// RFC 7396 JSON Merge Patch
function mergePatch(target, patch) {
  if (patch === null || typeof patch !== 'object' || Array.isArray(patch)) return patch;
  const result = (target && typeof target === 'object' && !Array.isArray(target)) ? { ...target } : {};
  for (const [key, value] of Object.entries(patch)) {
    if (value === null) delete result[key];
    else result[key] = mergePatch(result[key], value);
  }
  return result;
}
const etag = (resource) => '"' + crypto.createHash('sha1').update(JSON.stringify(resource)).digest('hex').slice(0, 8) + '"';

let student = { id: 1, name: 'Asha', city: 'Pune', tags: ['a', 'b'], address: { street: 'MG Road', zip: '411001' } };
console.log('original      :', JSON.stringify(student));
console.log('PUT body      :', JSON.stringify({ id: 1, name: 'Asha Rao' }), '-> everything else is gone');
console.log('PATCH changes :', JSON.stringify(mergePatch(student, { name: 'Asha Rao', city: null, tags: ['c'], address: { zip: '411002' } })));

// A write with If-Match
function update(current, ifMatch, patch) {
  if (ifMatch !== etag(current)) return { status: 412 };
  return { status: 200, resource: mergePatch(current, patch) };
}
const tagSeenByBoth = etag(student);
const first = update(student, tagSeenByBoth, { name: 'First writer' });
student = first.resource;
const second = update(student, tagSeenByBoth, { name: 'Second writer' });
console.log('first write   :', first.status, '| second write with a stale ETag:', second.status);
console.log('ETag changed  :', tagSeenByBoth !== etag(student));

The Merge Patch function and the ETag check are written in plain Node with no server, so the logic is easy to read. In a real API they sit behind the PATCH route and the If-Match header. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): original : {"id":1,"name":"Asha","city":"Pune","tags":["a","b"],"address":{"street":"MG Road","zip":"411001"}} PUT body : {"id":1,"name":"Asha Rao"} -> everything else is gone PATCH changes : {"id":1,"name":"Asha Rao","tags":["c"],"address":{"street":"MG Road","zip":"411002"}} first write : 200 | second write with a stale ETag: 412 ETag changed : true

Key points

  • PUT replaces the whole resource; PATCH changes part of it.
  • Merge Patch: null deletes, objects merge, arrays replace.
  • JSON Patch is an explicit list of operations.
  • ETag plus If-Match gives optimistic concurrency over HTTP.
  • A failed precondition is 412.

Common mistakes

  • Using PUT with a partial body and deleting fields by accident.
  • Using Merge Patch when you need to set null or edit an array item.
  • Using last-write-wins updates in a multi-user app.
  • Computing an ETag from something that changes on every request.
  • Answering 409 for every conflict (412 is the precondition code).

Follow-ups

  • When is JSON Patch better than Merge Patch?
  • What is a weak ETag?
  • How does If-None-Match work for caching?

Tips

  • Define each method in one line.
  • Mention null as delete in Merge Patch.
  • Tie ETag to lost updates.