Back to results for “Error Handling”
Node.js › Databases

What is optimistic concurrency control, and how would you implement it to prevent lost updates when two users edit the same record simultaneously?

Advanced

Answer

Optimistic concurrency control lets multiple users read and attempt to update the same record without locking it, but detects conflicting concurrent updates at write time (commonly via a version number or timestamp column that must match the value originally read) -- if another update has happened in between, the write is rejected and the conflicting user must reload the current data and retry, preventing one user's update from silently overwriting another's without either party realizing it.
async function updateDocument(id, expectedVersion, newContent) {
  const result = await db.documents.updateOne(
    { _id: id, version: expectedVersion },
    { $set: { content: newContent }, $inc: { version: 1 } }
  );
  if (result.modifiedCount === 0) throw new Error('Conflict: document was modified by someone else');
}
Real-world example A collaborative document-editing feature includes a version number with every edit request; if a user submits an edit based on an outdated version (because someone else already saved a change), the update is rejected with a conflict error rather than silently overwriting the other user's changes.

Common follow-ups: How does optimistic concurrency control differ from pessimistic locking, and when is each more appropriate?;What should the user experience be when a conflict is detected -- how do you help them resolve it?