# Optimistic locking

## What it is

Optimistic locking detects conflicting writes by checking a version from the
read when an update is attempted. A client reads a record and gets a version
token with it. At write time, the data store changes the row only if the stored
version still matches the expected one. The check and the write need one atomic
operation. A common implementation updates a row with a predicate on both its
identifier and its original version, and then advances the version in the same
statement.

For example, two people can open the details for a delivery address at version
12. One person changes the street number and saves version 13. The other user
submits a form still based on version 12. A conditional write catches that the
submitted version is stale. The application can offer the current value and the
pending edit for comparison. The version could instead be a data-store-generated
token with equality semantics. It needs to change on writes the application
intends to treat as conflicts.

The technique assumes that overlapping edits are infrequent enough to handle
after they occur. Readers can take time to consider an edit without reserving
the record for the entire interaction. The database may still lock rows
internally while it performs the conditional update. The word optimistic refers
to how the application handles the gap between read and write. A transaction
isolation level governs how several operations interact, while the predicate
checks whether this edit is still based on the current version.

## Why it matters

Overwriting an intervening change silently can lose work while leaving a
database in an apparently consistent state. Every value may still satisfy its
type and constraints. An optimistic version check makes the loss visible at the
moment the later update is attempted. The caller can give a useful response to
the person or process making that edit. It can also log how often a certain
operation competes with another so developers can see whether the design costs
users time.

The operation that follows a conflict depends on the meaning of the command.
Adding one to a counter may be safe to recompute on current state if the request
is still valid and its identity is tracked. Replacing a whole set of delivery
instructions requires more care. Applying the same replacement after fetching a
current version could discard the person's intervening edit and defeat the
check. Decide which changes may be merged by rule and which need a new decision
by the user.

Version checks are useful across an HTTP boundary. An API can issue a strong
entity tag and require the caller to send it in If-Match for a conditional
modification. HTTP defines what happens when that precondition fails. The
implementation still has to bind the request token to the version used by the
storage operation. Checking the request in one service and then writing
unconditionally to the database reopens the interval in which another writer can
change the row.

## What it looks like in practice

Set up two independent clients in a test of the delivery address editor. Read
the same address and token in both clients. Submit the first correction, wait
for the write, then submit another correction with the original token. Assert
that the first change remains present, the second request reports a conflict and
the version has advanced as expected. Read back the database and the newly
displayed form. A meaningful conflict should show enough of the current state
for the person to decide how to proceed.

Extend the exercise to a deletion while the second client is editing. Decide
whether the application distinguishes a missing record from one that changed,
and how it communicates that result without revealing inaccessible records. Test
version changes from background workers and batch imports as well as publicly
exposed edits. If either can modify the same fields, include their writes in the
version policy. Otherwise a particular route can undermine the lock even though
the editor itself passes.

Our
[case study on testing migrations for schema drift](/portfolio/1022-migrations-behind-a-schema-drift-gate/)
compares a fresh database with one that has replayed its migrations, including
seeded data. A system adding a version field can use that testing discipline to
verify consistent default values and constraints across its installation paths.
The delivery editor is an example of conflict detection. An integration test for
competing updates checks a different property from the case study's schema
comparison, and both can be run when a version field is introduced.

## Where it goes wrong

A service can fetch a row, compare its version in application code and issue an
update with a predicate only on the row identifier. That separates the
comparison from the change. A competing write can land between them. Use the
database's conditional write or a verified mechanism provided by the persistence
library. In tests, inspect the affected row count or reported conflict and
assert the stored result. An apparently successful response with no changed row
is still a failure for the caller.

A row version protects the writes associated with that row. A rule spanning
several rows may need a transaction, a database constraint or a separately
locked resource. For example, a limit shared by two warehouses can be exceeded
even if each warehouse row passes its own version check. Specify the invariant
first, including the case where different parts of it change in concurrent
transactions.

If conflicts happen often, repeating the entire operation can overload the
service and still leave several users competing for the same version. Cap
retries for commands that can safely be recomputed, and measure the conflict
rate and the time spent repeating work. A smaller unit of change, an atomic
operation for a common update, or deliberate serialization can fit a heavily
contested record better. Test the chosen strategy under the traffic pattern that
causes the conflict.

## Further reading

- [Jakarta Persistence on entity locking](https://jakarta.ee/learn/jakartaee-tutorial/current/persist/persistence-locking/persistence-locking.html)
  describes version checks and optimistic lock exceptions.
- [EF Core concurrency conflicts](https://learn.microsoft.com/en-us/ef/core/saving/concurrency)
  shows conditional writes and approaches to resolving conflicts.
- [HTTP conditional requests](https://www.rfc-editor.org/rfc/rfc9110.html#name-if-match)
  specifies how clients can use If-Match to prevent lost updates.

<https://engineer.company/glossary/optimistic-locking/>
