{"canonical_url":"https://engineer.company/glossary/optimistic-locking/","content_markdown":"# Optimistic locking\n\n## What it is\n\nOptimistic locking detects conflicting writes by checking a version from the\nread when an update is attempted. A client reads a record and gets a version\ntoken with it. At write time, the data store changes the row only if the stored\nversion still matches the expected one. The check and the write need one atomic\noperation. A common implementation updates a row with a predicate on both its\nidentifier and its original version, and then advances the version in the same\nstatement.\n\nFor example, two people can open the details for a delivery address at version\n12. One person changes the street number and saves version 13. The other user\nsubmits a form still based on version 12. A conditional write catches that the\nsubmitted version is stale. The application can offer the current value and the\npending edit for comparison. The version could instead be a data-store-generated\ntoken with equality semantics. It needs to change on writes the application\nintends to treat as conflicts.\n\nThe technique assumes that overlapping edits are infrequent enough to handle\nafter they occur. Readers can take time to consider an edit without reserving\nthe record for the entire interaction. The database may still lock rows\ninternally while it performs the conditional update. The word optimistic refers\nto how the application handles the gap between read and write. A transaction\nisolation level governs how several operations interact, while the predicate\nchecks whether this edit is still based on the current version.\n\n## Why it matters\n\nOverwriting an intervening change silently can lose work while leaving a\ndatabase in an apparently consistent state. Every value may still satisfy its\ntype and constraints. An optimistic version check makes the loss visible at the\nmoment the later update is attempted. The caller can give a useful response to\nthe person or process making that edit. It can also log how often a certain\noperation competes with another so developers can see whether the design costs\nusers time.\n\nThe operation that follows a conflict depends on the meaning of the command.\nAdding one to a counter may be safe to recompute on current state if the request\nis still valid and its identity is tracked. Replacing a whole set of delivery\ninstructions requires more care. Applying the same replacement after fetching a\ncurrent version could discard the person's intervening edit and defeat the\ncheck. Decide which changes may be merged by rule and which need a new decision\nby the user.\n\nVersion checks are useful across an HTTP boundary. An API can issue a strong\nentity tag and require the caller to send it in If-Match for a conditional\nmodification. HTTP defines what happens when that precondition fails. The\nimplementation still has to bind the request token to the version used by the\nstorage operation. Checking the request in one service and then writing\nunconditionally to the database reopens the interval in which another writer can\nchange the row.\n\n## What it looks like in practice\n\nSet up two independent clients in a test of the delivery address editor. Read\nthe same address and token in both clients. Submit the first correction, wait\nfor the write, then submit another correction with the original token. Assert\nthat the first change remains present, the second request reports a conflict and\nthe version has advanced as expected. Read back the database and the newly\ndisplayed form. A meaningful conflict should show enough of the current state\nfor the person to decide how to proceed.\n\nExtend the exercise to a deletion while the second client is editing. Decide\nwhether the application distinguishes a missing record from one that changed,\nand how it communicates that result without revealing inaccessible records. Test\nversion changes from background workers and batch imports as well as publicly\nexposed edits. If either can modify the same fields, include their writes in the\nversion policy. Otherwise a particular route can undermine the lock even though\nthe editor itself passes.\n\nOur\n[case study on testing migrations for schema drift](/portfolio/1022-migrations-behind-a-schema-drift-gate/)\ncompares a fresh database with one that has replayed its migrations, including\nseeded data. A system adding a version field can use that testing discipline to\nverify consistent default values and constraints across its installation paths.\nThe delivery editor is an example of conflict detection. An integration test for\ncompeting updates checks a different property from the case study's schema\ncomparison, and both can be run when a version field is introduced.\n\n## Where it goes wrong\n\nA service can fetch a row, compare its version in application code and issue an\nupdate with a predicate only on the row identifier. That separates the\ncomparison from the change. A competing write can land between them. Use the\ndatabase's conditional write or a verified mechanism provided by the persistence\nlibrary. In tests, inspect the affected row count or reported conflict and\nassert the stored result. An apparently successful response with no changed row\nis still a failure for the caller.\n\nA row version protects the writes associated with that row. A rule spanning\nseveral rows may need a transaction, a database constraint or a separately\nlocked resource. For example, a limit shared by two warehouses can be exceeded\neven if each warehouse row passes its own version check. Specify the invariant\nfirst, including the case where different parts of it change in concurrent\ntransactions.\n\nIf conflicts happen often, repeating the entire operation can overload the\nservice and still leave several users competing for the same version. Cap\nretries for commands that can safely be recomputed, and measure the conflict\nrate and the time spent repeating work. A smaller unit of change, an atomic\noperation for a common update, or deliberate serialization can fit a heavily\ncontested record better. Test the chosen strategy under the traffic pattern that\ncauses the conflict.\n\n## Further reading\n\n- [Jakarta Persistence on entity locking](https://jakarta.ee/learn/jakartaee-tutorial/current/persist/persistence-locking/persistence-locking.html)\n  describes version checks and optimistic lock exceptions.\n- [EF Core concurrency conflicts](https://learn.microsoft.com/en-us/ef/core/saving/concurrency)\n  shows conditional writes and approaches to resolving conflicts.\n- [HTTP conditional requests](https://www.rfc-editor.org/rfc/rfc9110.html#name-if-match)\n  specifies how clients can use If-Match to prevent lost updates.\n\n\u003chttps://engineer.company/glossary/optimistic-locking/\u003e\n","date_modified":"2026-11-24T21:48:58Z","description":"How version checks detect competing edits, when a retry makes sense, and how to test a write conflict.","formats":{"gemtext":"https://engineer.company/glossary/optimistic-locking/index.gmi","gopher":"https://engineer.company/glossary/optimistic-locking/gophermap","html":"https://engineer.company/glossary/optimistic-locking/","json":"https://engineer.company/glossary/optimistic-locking/index.json","markdown":"https://engineer.company/glossary/optimistic-locking/index.md","pdf":"https://engineer.company/glossary/optimistic-locking/index.pdf"},"kind":"page","language":"en","title":"What is optimistic locking?","url":"https://engineer.company/glossary/optimistic-locking/","version":1}