Most writing about concurrency control uses counters: stock levels, balances, seat reservations. Those are machine writes, done in milliseconds, and the right tool is usually an atomic UPDATE or a short SELECT ... FOR UPDATE. This post is about a different kind of write: a person opens a form, edits for a few minutes, and presses Save. Meanwhile a colleague edited the same record.

That is where optimistic locking with a version column fits, and where it is often implemented halfway.

The problem: last save wins

Two support agents open customer 7731 at 10:00. Agent A changes the shipping address and saves at 10:03. Agent B, who opened the record at the same time and only meant to add a note, saves at 10:05. B's form still contained the old address, so B's save writes the old address back. A's change is gone, and neither of them knows.

This is a lost update. A database lock cannot prevent it in any practical way: holding a row lock from 10:00 to 10:05, across two HTTP requests and a person thinking, would mean holding a transaction open for minutes. Connections, locks and timeouts are not designed for that.

How a version column works

Add an integer column that changes on every write:

ALTER TABLE customers ADD COLUMN version integer NOT NULL DEFAULT 1;

When the form loads, the client receives the version along with the data. When it saves, it sends the version it started from, and the update only succeeds if the row still has that version:

UPDATE customers
SET    name = :name, shipping_address = :address, notes = :notes,
       version = version + 1, updated_at = now()
WHERE  id = :id AND version = :expected_version;

Then check the number of affected rows:

  • 1 row: the save succeeded. The new version is expected_version + 1.
  • 0 rows: either the record does not exist, or someone else saved first. A quick lookup by id tells the two apart.

In the example, both agents loaded version 4. A's save matches version = 4, succeeds, and makes it 5. B's save asks for version = 4, matches nothing, and is rejected. Nothing is lost.

The check and the increment happen in one statement, so the update itself is atomic and needs no extra locking. "Optimistic" refers to the assumption that conflicts are rare: you do not block anyone up front, you detect the conflict at the end.

Why a version number and not updated_at

Using WHERE updated_at = :expected looks equivalent and is tempting because the column usually exists already. It is fragile: two writes in the same clock tick get the same timestamp, timestamp precision differs between engines and drivers (MySQL DATETIME without fractional seconds rounds to the second), and clock adjustments can move time backwards. An integer that only ever increments has none of these problems.

Exposing it over HTTP

For an API, the version maps naturally to HTTP conditional requests:

GET /customers/7731
200 OK
ETag: "v4"
PUT /customers/7731
If-Match: "v4"
Content-Type: application/json

{ "name": "...", "shipping_address": "...", "notes": "..." }

If the version no longer matches, the server answers 412 Precondition Failed. Requiring If-Match on writes (and returning 428 Precondition Required when it is missing) makes it impossible for a client to skip the check by accident.

Most ORMs support this pattern out of the box: JPA/Hibernate's @Version, Entity Framework's concurrency tokens, Rails' lock_version, Django via a conditional filter(version=...).update(...). Using the built-in support is better than hand-rolling it, as long as you also handle the failure properly, which is the part usually skipped.

When to retry automatically

A rejected save means "your input was based on old data". Whether to retry depends on who produced that input.

Retry automatically when the write is computed by code from the current state. A background job that recalculates a customer's loyalty tier can simply re-read the record and recompute:

def recalculate_tier(customer_id: int, attempts: int = 3) -> None:
    for _ in range(attempts):
        c = repo.get(customer_id)
        tier = compute_tier(c.lifetime_spend)
        if repo.update_if_version(customer_id, c.version, tier=tier):
            return
    raise ConflictError(f"customer {customer_id} kept changing")

The retry re-reads first. Retrying the same UPDATE with the same stale data would just fail again, or worse, succeed with stale input if the version check were dropped.

Under high contention, retries can spin. A small number of attempts with a short random delay is enough for occasional conflicts. If a record is genuinely hot (updated many times per second), optimistic locking is the wrong tool, as below.

Do not retry automatically when a person produced the input. The person made decisions based on what they saw. Silently re-applying their whole form on top of someone else's changes is exactly the lost update we set out to prevent.

Showing a conflict to a person

A message like "Someone else changed this record. Please reload" is correct and frustrating: reloading throws away the user's edits. Better options, roughly in order of effort:

  1. Keep their input and show what changed. Reload the current record, keep the user's form values, and highlight the fields where the stored value now differs from what they started with. They decide per field.
  2. Merge automatically when the changes do not overlap. If the user only changed notes and the other save only changed shipping_address, apply just the user's changed fields on top of the new version. This needs the original values the form loaded with, so the server can compute which fields the user actually changed.
  3. Show presence. "Ana is also editing this record" when a second person opens it. This reduces conflicts but does not replace the check.

For option 2, the client sends the fields it changed and their original values:

{
  "expected_version": 4,
  "changes": {
    "notes": { "from": "VIP since 2023", "to": "VIP since 2023. Prefers email." }
  }
}

The server loads the current record (version 5). For each changed field, if the current value still equals from, it applies to. If any field's current value differs from from, that field is a real conflict and goes back to the user. Then it saves with expected_version = 5, which is still checked, because another save could arrive during the merge.

We implemented option 1 everywhere and option 2 for the three screens where conflicts were most common. Support tickets about "my changes disappeared" stopped.

When pessimistic locking fits better

Optimistic locking is not always better. A comparison from our own systems:

Situation Better choice Why
Person edits a record for minutes optimistic no lock can be held that long
Many automated writes to the same row per second atomic UPDATE ... SET x = x + 1 or FOR UPDATE optimistic retries would spin
Read several rows, decide, write within one request SELECT ... FOR UPDATE in a short transaction simpler, no retry loop
Exclusive editing required (legal documents) an explicit application-level checkout with expiry the business wants "only one editor", not conflict detection

The last row is worth highlighting. If the business rule is "only one person may edit a contract at a time", that is not a concurrency problem to solve with database locks. It is a feature: a checked_out_by and checked_out_until on the record, shown in the UI, with an expiry so an abandoned browser tab does not block everyone forever.

Testing it

Two tests cover the important behaviour:

def test_second_save_with_stale_version_is_rejected(client, customer):
    v = client.get(f"/customers/{customer.id}").headers["ETag"]
    assert client.put(f"/customers/{customer.id}", json=edit(address="New 1"),
                      headers={"If-Match": v}).status_code == 200
    r = client.put(f"/customers/{customer.id}", json=edit(notes="hello"),
                   headers={"If-Match": v})
    assert r.status_code == 412
    assert client.get(f"/customers/{customer.id}").json()["address"] == "New 1"

def test_write_without_if_match_is_refused(client, customer):
    assert client.put(f"/customers/{customer.id}", json=edit(notes="x")).status_code == 428

The first test is exactly the support-agent scenario from the top of this post.

Summary

  • For records people edit over minutes, use a version column and UPDATE ... WHERE version = ?, then check the affected row count.
  • Use an integer version, not updated_at.
  • Over HTTP, use ETag and If-Match, and require If-Match on writes.
  • Retry automatically only when code computes the write from fresh data. For human input, show the conflict, keep their edits, and merge non-overlapping fields where you can.
  • For hot rows and short machine writes, atomic updates or FOR UPDATE remain the better tools.

References: RFC 9110 conditional requests, RFC 6585, 428 Precondition Required, Hibernate optimistic locking, PostgreSQL UPDATE.