⚙️ Optimistic Locking Explained: How Applications Prevent Users from Accidentally Overwriting Each Other’s Data

⚙️ Optimistic Locking Explained: How Applications Prevent Users from Accidentally Overwriting Each Other’s Data

Imagine two customer-support agents opening the same account record. One corrects the customer’s address while the other updates a phone number. Both see a familiar form, both click Save, and neither realizes that someone else is editing the record at the same time.

If the application simply accepts both requests, the second save may replace the first agent’s changes with an older copy of the whole record. The address correction disappears, even though no one intended to delete it.

This is a lost update: one user’s valid change is silently overwritten by another concurrent change. It can affect shopping carts, schedules, invoices, settings, documents, and nearly any record edited by more than one person or process.

Optimistic locking is a practical way to detect that conflict before data is lost. Rather than preventing people from working at the same time, it checks whether the data changed between reading it and writing it.

🧩 The problem is concurrent editing

Concurrency means more than two people typing in a browser. A user, background job, API client, mobile app, and administrator may all act on the same row within a short period.

Most web applications follow a read-edit-write pattern. They load a record, let work happen outside the database transaction, then send an update later. That gap creates an opportunity for another update to arrive first.

💥 What a lost update looks like

Suppose a product currently has a price of 50 and a description of “Standard plan.” Maya loads it. While she is editing the description, Ben changes the price to 60 and saves.

Maya’s browser still holds the older object: price 50, old description. If her save writes every field without checking, it can store price 50 again along with her improved description. Ben’s change is lost.

The dangerous part is silence. Both users see a successful save, yet the database no longer represents all intended work.

🌤️ Why the approach is called optimistic

Optimistic locking starts with an assumption: conflicts are possible, but uncommon enough that users should be allowed to work independently. It does not reserve a record when somebody opens an edit page.

Instead, the application proceeds optimistically and validates its assumption at save time. If nobody changed the record, the update succeeds. If somebody did, the application detects the mismatch and asks for a recovery path.

🔢 The version field is the usual mechanism

The most common design adds a version column to a table. It might be an integer named version, revision, or lock_version.

Every stored record carries its current version. When an application reads the row, it also reads that value. When it later submits an edit, it includes the version it originally saw.

id: 42
name: "Standard plan"
price: 50
version: 7

The version is not business data. It is a small piece of concurrency metadata that says which revision of the record the editor worked from.

🔍 The conditional update is the real lock

A version field alone prevents nothing. The protection comes from using it in the update condition, often called compare-and-swap: update only if the stored version still equals the expected version.

UPDATE products
SET description = ?, version = version + 1
WHERE id = ? AND version = ?;

If the query affects one row, the record had the expected version and the update can proceed. If it affects zero rows, either the record is gone or its version changed. The application must treat that outcome as a conflict, not as a normal success.

🕒 A step-by-step conflict timeline

  1. Agent A and Agent B both read order 101 at version 12.
  2. Agent A changes the delivery note and saves with expected version 12.
  3. The database updates the row and advances it to version 13.
  4. Agent B changes the contact number and saves with expected version 12.
  5. B’s conditional update affects zero rows because version 12 is no longer current.

Agent B has not overwritten A. The system now has a chance to reload current data, compare changes, or let B decide what to do next.

🧠 Detection is not automatic merging

Optimistic locking detects that the editor’s starting point is stale. It does not know whether the competing changes are compatible.

In the example, a delivery note and contact number may be safely combined. But two different edits to an invoice total, stock quantity, or approval state may need a business rule rather than a mechanical merge.

Keeping conflict detection separate from conflict resolution makes designs clearer. The database protects correctness; the application chooses a suitable user experience.

🗃️ Version numbers versus timestamps

A timestamp such as updated_at can also represent the revision an editor observed. The client sends the timestamp back, and the update succeeds only if it still matches.

Approach Strength Common caution
Integer version Clear ordering and reliable increment Must increment it on every relevant update
Timestamp May already exist for auditing Precision, formatting, and clock assumptions can complicate comparisons
Entity tag (ETag) Fits HTTP resources well Server must define and consistently validate it

Integer versions are often the simplest choice for database-backed records. Timestamps can work, but equal timestamps or precision differences can make an apparently simple design fragile.

🌐 HTTP APIs can use ETags

For a REST-style HTTP API, the server can return an ETag, an opaque identifier for a resource representation. A client sends it back in an If-Match header when it wants to update or delete that resource.

PATCH /customers/42
If-Match: "revision-7"

If the ETag no longer matches, the server can reject the request with 412 Precondition Failed. The principle is identical to a version-column check: only apply my change if the state I read is still current.

📱 Mobile and offline clients need it even more

Mobile apps may hold data for minutes, hours, or longer while connectivity is unreliable. Offline-first software intentionally allows edits without an immediate server round trip.

That makes stale writes normal rather than exceptional. Store a base revision with each local edit, synchronize with a conditional write, and design a conflict workflow appropriate to the kind of data being changed.

🔒 Optimistic locking is not a database lock

The word “locking” can mislead newcomers. Optimistic locking usually does not hold a database row lock while a person stares at an edit form.

A database may briefly lock rows while executing an update as part of its normal transaction handling. But the optimistic strategy itself is a validation protocol across the longer interval between read and save.

🚧 Pessimistic locking takes the other path

Pessimistic locking assumes a conflict is likely or too costly to resolve later. It acquires a lock early, perhaps with a database command such as SELECT ... FOR UPDATE, so competing transactions wait or fail.

This can be appropriate for short, tightly controlled transactional work. It is generally a poor fit for long-lived browser editing because locks consume resources and can cause queues, timeouts, or deadlocks.

⚖️ Choosing between optimistic and pessimistic approaches

Neither approach is universally superior. The right choice depends on contention, duration, and what an incorrect outcome would cost.

  • Prefer optimistic locking when edits are relatively infrequent and users can retry or merge.
  • Consider pessimistic locking for short operations where simultaneous changes must be serialized immediately.
  • Use domain-specific coordination when a real-world resource must be reserved, such as a seat, appointment slot, or limited inventory allocation.

Some systems use both in different places. A CMS article may use optimistic locking, while a payment workflow relies on carefully scoped transactions and idempotency controls.

🧾 Partial updates do not eliminate conflicts

Sending only changed fields reduces the chance that one request overwrites unrelated columns. It is a useful API design practice, but it does not replace concurrency control.

Two partial updates can still conflict over the same field or violate a cross-field rule. For example, changing an order status and changing its cancellation reason may need to be evaluated as one coherent state transition.

🧮 Business invariants need additional protection

A version check protects one record from being replaced with a stale copy. It does not automatically preserve rules involving multiple rows or computed totals.

Consider two people each reserving the last available unit based on an earlier inventory count. Both may update different reservation rows successfully while the system oversells stock unless the inventory rule is enforced transactionally.

Use database constraints, appropriate transaction isolation, atomic updates, or a deliberate reservation design for these cases. Optimistic locking is one tool, not a complete consistency model.

🛠️ ORMs often support versioned entities

Many object-relational mappers (ORMs) can designate a property as a version field. The ORM includes it in generated update conditions and raises a concurrency exception when no row matches.

That convenience is valuable, but inspect the generated SQL and framework behavior. You need to know when the version increments, whether bulk operations bypass checks, and how an exception reaches the application layer.

⚠️ Bulk updates can bypass safeguards

Administrative scripts and ORM bulk-update methods often operate directly on sets of rows. They may not load entities, check each version, or trigger normal lifecycle hooks.

That can be correct for carefully designed maintenance work, but it should be intentional. If a bulk change modifies data that users edit, decide whether it increments versions, excludes active records, or coordinates with the normal write path.

🧪 Test the race, not just the happy path

A basic unit test can verify that a stale version produces a conflict. A stronger integration test uses two separate database sessions: both read a record, the first saves, and the second attempts to save the original revision.

Also test deletion, retries, background writers, API clients, and ORM bulk behavior. Concurrency defects frequently hide because ordinary manual testing happens one request at a time.

🖥️ Give people a useful conflict message

“Update failed” gives a user no useful next action. Explain that the record changed while they were editing and make the next step clear.

  • Reload current data when the user’s changes can be discarded safely.
  • Show a field-by-field comparison for valuable free-form work.
  • Offer a merge or “apply my non-conflicting changes” action where the product can do so reliably.
  • Preserve unsaved input so a rejected request does not create a second loss.

A conflict is often normal collaboration, not a user error.

📝 Rich text and documents need specialized merging

For a short settings form, reloading after a conflict may be enough. For long notes, source code, or shared documents, forcing a person to recreate an edit can be unacceptable.

Three-way merge compares a common base version with each person’s changes. More advanced real-time editors may use operational transformation or conflict-free replicated data types (CRDTs). Those techniques solve broader synchronization problems and add complexity beyond a simple row version.

🔁 Retries must be deliberate

Some conflicts are safe to retry automatically. For example, a worker that adds a commutative event to a log may reload state and try again under well-defined rules.

Blindly retrying a user’s stale “set status to approved” request can be wrong if another user changed the status to cancelled. Retry only when the operation is known to be safe after re-reading current state.

📦 Idempotency solves a different problem

An idempotent request can be sent more than once without causing the operation to happen twice. Payment APIs often use idempotency keys so network retries do not create duplicate charges.

Optimistic locking answers a different question: “Has the state changed since I read it?” Robust systems may need both. A request can be non-duplicating yet still stale, or current yet accidentally repeated.

🧭 Model commands, not just record replacements

APIs that accept a complete serialized object invite clients to think in terms of replacement. In many domains, a command expresses intent more clearly: cancelOrder, assignReviewer, or increaseQuantity.

Commands can validate the current state and enforce domain rules in one transaction. They still may use a version precondition, but the conflict response can be specific: “This order cannot be cancelled because it has already shipped.”

📊 Monitor conflicts as product feedback

Record concurrency failures with enough context to investigate: entity type, operation, endpoint, and whether the conflict came from a person or an automated process. Avoid logging sensitive record contents unnecessarily.

A rising conflict rate may reveal a workflow issue, a noisy background process, a page that remains open too long, or a record that has become a shared bottleneck. The answer might be better UI design rather than a different database primitive.

🧱 Keep the check close to the write

A common mistake is comparing a version in application memory and then issuing an unconditional update. Another request can modify the row between those two operations.

The comparison and write must be one atomic database operation, or be protected by an equivalent transactional mechanism. The conditional WHERE clause matters precisely because the database evaluates it at update time.

🚫 Do not treat zero updated rows as success

Some data-access layers return an affected-row count that developers ignore. With optimistic locking, that count carries essential information.

Zero rows can mean a stale revision, a deleted record, an authorization filter, or an incorrect identifier. Distinguish these cases when practical, but never report a successful update before understanding why no row changed.

🧹 Decide which changes advance the version

Usually every change that a concurrent editor should notice increments the version. That includes changes made by background jobs when they alter user-visible or business-relevant state.

Some teams exclude purely technical fields, such as a last-access timestamp, to avoid needless conflicts. The rule should be explicit: a version represents the set of changes that make a previously read editing view unreliable.

🧩 Handle parent and child data carefully

A screen may edit an order and its line items together, even though they live in several tables. A version only on the parent does not automatically detect a child-row update unless the parent revision changes too.

Choose a consistency boundary. You might version each child independently, advance an aggregate version whenever any child changes, or make the command validate the relevant set of revisions. The right boundary follows how users reason about the data.

🗺️ A practical implementation checklist

  • Add a revision field to records that have meaningful concurrent edits.
  • Return that revision whenever clients read an editable representation.
  • Require the expected revision on update and delete operations.
  • Perform an atomic conditional write that advances the revision.
  • Translate a mismatch into a clear concurrency outcome.
  • Provide a recovery experience that preserves user work.
  • Test two writers against the same original revision.
  • Document exceptions for bulk jobs and system-managed updates.

This creates a consistent contract across browsers, services, scripts, and mobile clients.

🎯 The core principle: detect stale assumptions before writing

Optimistic locking does not stop people from editing simultaneously, and it cannot decide every business conflict. What it does exceptionally well is prevent an old view of a record from silently replacing a newer one.

Its essential contract is simple: “Apply this change only if the data is still the revision I originally read.” From there, the application can reload, merge, retry safely, or ask a person to make an informed decision.

When data can be edited concurrently, a conditional write turns silent loss into a visible, manageable conflict. That is a small database pattern with a large effect on trust in software. ⚙️🔐🤝