Programming Search⌘K

Patterncore

Optimistic offline lock

Also called Optimistic Offline Lock, optimistic locking, optimistic concurrency control, version check, lock_version.

An optimistic offline lock gives each record a version. A save checks that the version did not change since the session read the record, and fails on a conflict.

Family
architectural
Intent
Prevent conflicts between concurrent business transactions by detecting a conflict and rolling back the transaction.

Intent

An optimistic offline lock "Prevents conflicts between concurrent business transactions by detecting a conflict and rolling back the transaction."1 Each record has a version. A session keeps the version that it read, and its save succeeds only if the version in the database is still the same.

Problem

A business transaction, such as the edit of a customer in a web form, often runs across many requests. Each request is a short system transaction of the database. The database keeps each system transaction correct, but it does not know about the business transaction. "Data integrity is at risk once two sessions begin to work on the same records and lost updates are quite possible."1

For example, Ann and Bob open the same customer. Bob changes the credit and saves. Then Ann changes the name and saves the whole record from the copy that Ann read. The database now has the old credit, and the change of Bob is lost. No error tells anyone about it.

An open system transaction for the whole business transaction is not a good solution. It holds the database locks while a user reads the form, and the user can leave the form open for a long time.

Solution

"Optimistic Offline Lock solves this problem by validating that the changes about to be committed by one session don't conflict with the changes of another session."1 The usual way is a version number in each row:

  • The version column. Each row has a number that each save increases by one.
  • The read. The session reads the row and keeps the version with its copy of the data. In a web application, the version goes into the form, often as a hidden field.
  • The checked save. The session writes the row only if the version is still the one that it read, and it increases the version in the same step. In SQL, this is UPDATE ... SET version = version + 1 WHERE id = ? AND version = ?. If no row changed, another session saved first.
  • The conflict. The save fails, the business transaction rolls back, and the application tells the user. The user can reload the new data and do the edit again.

The check and the write must be one step. "So long as the validation and the updates occur within a single system transaction the business transaction will display consistency."1

  business transaction of bob            business transaction of ann
  request 1: read customer 1, version 1  request 1: read customer 1, version 1
  request 2: UPDATE ... WHERE version = 1
             1 row changed, now version 2
                                         request 2: UPDATE ... WHERE version = 1
                                                    0 rows changed: conflict

In the following program, both sessions read version 1. The save of Bob changes the version, so the save of Ann finds a conflict.

table = {1: {"credit": 500, "version": 1}}


def save(customer_id, credit, read_version):
    row = table[customer_id]
    if row["version"] != read_version:  # someone saved since this session read the row
        return "conflict"
    table[customer_id] = {"credit": credit, "version": read_version + 1}
    return "ok"


ann_version = bob_version = table[1]["version"]  # both sessions read version 1
print("bob:", save(1, 800, bob_version))
print("ann:", save(1, 600, ann_version))
print(table[1])
Output
bob: ok
ann: conflict
{'credit': 800, 'version': 2}

Example

Each example file has a table of customers with a version column. Ann and Bob load customer 1, and both copies have version 1. Bob saves a new credit of 800, and the version becomes 2. Ann then saves a new name, but the copy of Ann still has version 1, so the save fails with a conflict. The session of Ann reloads the customer, Ann does the edit again on the new data, and the save succeeds with version 3. At the end, the customer has the new name and the new credit, so no change is lost.

PythonGitHub
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table customer (id integer primary key, name text, credit integer, version integer);
insert into customer values (1, 'Acme Ltd', 500, 1);
""")


class ConflictError(Exception):
    pass


# Each session reads the record in one system transaction and saves it in a later one.
# The version that it read goes with its copy of the data.
def load(customer_id):
    name, credit, version = db.execute(
        "select name, credit, version from customer where id = ?", (customer_id,)).fetchone()
    return {"id": customer_id, "name": name, "credit": credit, "version": version}


def save(copy):
    with db:  # the check and the update run in one system transaction
        cur = db.execute(
            "update customer set name = ?, credit = ?, version = version + 1 where id = ? and version = ?",
            (copy["name"], copy["credit"], copy["id"], copy["version"]))
        if cur.rowcount == 0:
            raise ConflictError(f"customer {copy['id']} was changed by another session")
    copy["version"] += 1


def show(c):
    return f"{c['name']}, credit {c['credit']}, version {c['version']}"


def try_save(who, copy, what):
    try:
        save(copy)
        print(f"{who} saves {what}: ok, version {copy['version']}")
        return True
    except ConflictError as e:
        print(f"{who} saves {what}: conflict: {e}")
        return False


ann = load(1)
print("ann loads customer 1:", show(ann))
bob = load(1)
print("bob loads customer 1:", show(bob))

bob["credit"] = 800
try_save("bob", bob, "credit 800")

ann["name"] = "Acme Group"
if not try_save("ann", ann, "name Acme Group"):
    ann = load(1)  # the session reloads, shows the new data, and the user does the edit again
    print("ann reloads:", show(ann))
    ann["name"] = "Acme Group"
    try_save("ann", ann, "name Acme Group")

print("final:", show(load(1)))
Output
ann loads customer 1: Acme Ltd, credit 500, version 1
bob loads customer 1: Acme Ltd, credit 500, version 1
bob saves credit 800: ok, version 2
ann saves name Acme Group: conflict: customer 1 was changed by another session
ann reloads: Acme Ltd, credit 800, version 2
ann saves name Acme Group: ok, version 3
final: Acme Group, credit 800, version 3
  • Verdict: idiom. The version is a column of the table. save runs one UPDATE with version = ? in its WHERE clause, inside with db:, so the check and the write are one step. When rowcount is 0, another session changed the row, and save raises ConflictError.
  • The session keeps the version with its copy of the data between the requests. In a web application, the version goes into a hidden field of the form.
JavaGitHub
import java.util.HashMap;
import java.util.Map;

public class Main {
    static class ConflictException extends RuntimeException {
        ConflictException(String message) { super(message); }
    }

    record Row(String name, int credit, int version) {}

    // A session's copy of the record, with the version that it read.
    static class Customer {
        final int id;
        String name;
        int credit;
        int version;
        Customer(int id, Row row) { this.id = id; name = row.name(); credit = row.credit(); version = row.version(); }
        @Override public String toString() { return name + ", credit " + credit + ", version " + version; }
    }

    // The table, kept in memory.
    static final Map<Integer, Row> table = new HashMap<>(Map.of(1, new Row("Acme Ltd", 500, 1)));

    static Customer load(int id) { return new Customer(id, table.get(id)); }

    // The check and the update are one step, like UPDATE ... WHERE version = ? in SQL.
    static synchronized void save(Customer c) {
        Row row = table.get(c.id);
        if (row.version() != c.version) throw new ConflictException("customer " + c.id + " was changed by another session");
        table.put(c.id, new Row(c.name, c.credit, row.version() + 1));
        c.version++;
    }

    static boolean trySave(String who, Customer c, String what) {
        try {
            save(c);
            System.out.println(who + " saves " + what + ": ok, version " + c.version);
            return true;
        } catch (ConflictException e) {
            System.out.println(who + " saves " + what + ": conflict: " + e.getMessage());
            return false;
        }
    }

    public static void main(String[] args) {
        Customer ann = load(1);
        System.out.println("ann loads customer 1: " + ann);
        Customer bob = load(1);
        System.out.println("bob loads customer 1: " + bob);

        bob.credit = 800;
        trySave("bob", bob, "credit 800");

        ann.name = "Acme Group";
        if (!trySave("ann", ann, "name Acme Group")) {
            ann = load(1); // the session reloads, shows the new data, and the user does the edit again
            System.out.println("ann reloads: " + ann);
            ann.name = "Acme Group";
            trySave("ann", ann, "name Acme Group");
        }

        System.out.println("final: " + load(1));
    }
}
Output
ann loads customer 1: Acme Ltd, credit 500, version 1
bob loads customer 1: Acme Ltd, credit 500, version 1
bob saves credit 800: ok, version 2
ann saves name Acme Group: conflict: customer 1 was changed by another session
ann reloads: Acme Ltd, credit 800, version 2
ann saves name Acme Group: ok, version 3
final: Acme Group, credit 800, version 3
  • Verdict: idiom. save is synchronized, so the check of the version and the write are one step. In Jakarta Persistence, a field with the @Version annotation gives the same check, and the provider throws an OptimisticLockException on a conflict.
  • ConflictException is unchecked. The session catches it, reloads the record and lets the user do the edit again.
JavaScriptGitHub
class ConflictError extends Error {}

// The table, kept in memory. Each row has a version number.
const table = new Map([[1, { name: "Acme Ltd", credit: 500, version: 1 }]]);

// Each session reads the record in one system transaction and saves it in a later one.
// The version that it read goes with its copy of the data.
function load(id) {
  return { id, ...table.get(id) };
}

function save(copy) {
  // The check and the update must be one step, like UPDATE ... WHERE version = ? in SQL.
  const row = table.get(copy.id);
  if (row.version !== copy.version) throw new ConflictError(`customer ${copy.id} was changed by another session`);
  table.set(copy.id, { name: copy.name, credit: copy.credit, version: row.version + 1 });
  copy.version++;
}

const show = (c) => `${c.name}, credit ${c.credit}, version ${c.version}`;

function trySave(who, copy, what) {
  try {
    save(copy);
    console.log(`${who} saves ${what}: ok, version ${copy.version}`);
    return true;
  } catch (e) {
    if (!(e instanceof ConflictError)) throw e;
    console.log(`${who} saves ${what}: conflict: ${e.message}`);
    return false;
  }
}

let ann = load(1);
console.log("ann loads customer 1:", show(ann));
const bob = load(1);
console.log("bob loads customer 1:", show(bob));

bob.credit = 800;
trySave("bob", bob, "credit 800");

ann.name = "Acme Group";
if (!trySave("ann", ann, "name Acme Group")) {
  ann = load(1); // the session reloads, shows the new data, and the user does the edit again
  console.log("ann reloads:", show(ann));
  ann.name = "Acme Group";
  trySave("ann", ann, "name Acme Group");
}

console.log("final:", show(load(1)));
Output
ann loads customer 1: Acme Ltd, credit 500, version 1
bob loads customer 1: Acme Ltd, credit 500, version 1
bob saves credit 800: ok, version 2
ann saves name Acme Group: conflict: customer 1 was changed by another session
ann reloads: Acme Ltd, credit 800, version 2
ann saves name Acme Group: ok, version 3
final: Acme Group, credit 800, version 3
  • Verdict: idiom. The table is a Map in memory, and save checks the version and writes the row with no await between the two steps, so no other code can run between them. With a database, the same check is an UPDATE with the version in the WHERE clause.
  • The session's copy is a new object made with the spread syntax, so a change to the copy does not change the table.
package main

import (
	"errors"
	"fmt"
	"sync"
)

var errConflict = errors.New("was changed by another session")

type row struct {
	name            string
	credit, version int
}

// Customer is a session's copy of the record, with the version that it read.
type Customer struct {
	id, credit, version int
	name                string
}

func (c Customer) String() string {
	return fmt.Sprintf("%s, credit %d, version %d", c.name, c.credit, c.version)
}

// Table is kept in memory. The mutex makes the check and the update one step,
// like UPDATE ... WHERE version = ? in SQL.
type Table struct {
	mu   sync.Mutex
	rows map[int]row
}

func (t *Table) Load(id int) Customer {
	t.mu.Lock()
	defer t.mu.Unlock()
	r := t.rows[id]
	return Customer{id: id, name: r.name, credit: r.credit, version: r.version}
}

func (t *Table) Save(c *Customer) error {
	t.mu.Lock()
	defer t.mu.Unlock()
	r := t.rows[c.id]
	if r.version != c.version {
		return fmt.Errorf("customer %d %w", c.id, errConflict)
	}
	t.rows[c.id] = row{c.name, c.credit, r.version + 1}
	c.version++
	return nil
}

func trySave(t *Table, who string, c *Customer, what string) bool {
	if err := t.Save(c); err != nil {
		fmt.Printf("%s saves %s: conflict: %v\n", who, what, err)
		return false
	}
	fmt.Printf("%s saves %s: ok, version %d\n", who, what, c.version)
	return true
}

func main() {
	t := &Table{rows: map[int]row{1: {"Acme Ltd", 500, 1}}}

	ann := t.Load(1)
	fmt.Println("ann loads customer 1:", ann)
	bob := t.Load(1)
	fmt.Println("bob loads customer 1:", bob)

	bob.credit = 800
	trySave(t, "bob", &bob, "credit 800")

	ann.name = "Acme Group"
	if !trySave(t, "ann", &ann, "name Acme Group") {
		ann = t.Load(1) // the session reloads, shows the new data, and the user does the edit again
		fmt.Println("ann reloads:", ann)
		ann.name = "Acme Group"
		trySave(t, "ann", &ann, "name Acme Group")
	}

	fmt.Println("final:", t.Load(1))
}
Output
ann loads customer 1: Acme Ltd, credit 500, version 1
bob loads customer 1: Acme Ltd, credit 500, version 1
bob saves credit 800: ok, version 2
ann saves name Acme Group: conflict: customer 1 was changed by another session
ann reloads: Acme Ltd, credit 800, version 2
ann saves name Acme Group: ok, version 3
final: Acme Group, credit 800, version 3
  • Verdict: idiom. A sync.Mutex makes the check of the version and the write one step. With database/sql, the same check is an UPDATE with the version in the WHERE clause, and RowsAffected tells whether it matched.
  • Save wraps errConflict with %w, so a caller can test for a conflict with errors.Is.
RustGitHub
use std::collections::HashMap;
use std::fmt;

struct Row {
    name: String,
    credit: i64,
    version: u32,
}

// A session's copy of the record, with the version that it read.
struct Customer {
    id: u32,
    name: String,
    credit: i64,
    version: u32,
}

impl fmt::Display for Customer {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}, credit {}, version {}", self.name, self.credit, self.version)
    }
}

struct Conflict(u32);

// The table, kept in memory. `save` takes `&mut self`, so the check and the update
// are one step, like UPDATE ... WHERE version = ? in SQL.
struct Table {
    rows: HashMap<u32, Row>,
}

impl Table {
    fn load(&self, id: u32) -> Customer {
        let r = &self.rows[&id];
        Customer { id, name: r.name.clone(), credit: r.credit, version: r.version }
    }

    fn save(&mut self, c: &mut Customer) -> Result<(), Conflict> {
        let r = self.rows.get_mut(&c.id).ok_or(Conflict(c.id))?;
        if r.version != c.version {
            return Err(Conflict(c.id));
        }
        *r = Row { name: c.name.clone(), credit: c.credit, version: r.version + 1 };
        c.version += 1;
        Ok(())
    }
}

fn try_save(t: &mut Table, who: &str, c: &mut Customer, what: &str) -> bool {
    match t.save(c) {
        Ok(()) => {
            println!("{} saves {}: ok, version {}", who, what, c.version);
            true
        }
        Err(Conflict(id)) => {
            println!("{} saves {}: conflict: customer {} was changed by another session", who, what, id);
            false
        }
    }
}

fn main() {
    let mut t = Table {
        rows: HashMap::from([(1, Row { name: "Acme Ltd".to_string(), credit: 500, version: 1 })]),
    };

    let mut ann = t.load(1);
    println!("ann loads customer 1: {}", ann);
    let mut bob = t.load(1);
    println!("bob loads customer 1: {}", bob);

    bob.credit = 800;
    try_save(&mut t, "bob", &mut bob, "credit 800");

    ann.name = "Acme Group".to_string();
    if !try_save(&mut t, "ann", &mut ann, "name Acme Group") {
        ann = t.load(1); // the session reloads, shows the new data, and the user does the edit again
        println!("ann reloads: {}", ann);
        ann.name = "Acme Group".to_string();
        try_save(&mut t, "ann", &mut ann, "name Acme Group");
    }

    println!("final: {}", t.load(1));
}
Output
ann loads customer 1: Acme Ltd, credit 500, version 1
bob loads customer 1: Acme Ltd, credit 500, version 1
bob saves credit 800: ok, version 2
ann saves name Acme Group: conflict: customer 1 was changed by another session
ann reloads: Acme Ltd, credit 800, version 2
ann saves name Acme Group: ok, version 3
final: Acme Group, credit 800, version 3
  • Verdict: idiom. save takes &mut self, so no other code can read or write the table between the check of the version and the write. A program with threads would put the table in a Mutex.
  • save returns a Result, and the caller must handle the conflict, because the compiler warns on a Result that is not used.

Consequences

Benefits.

  • No lost updates. A save that would write over a change of another session fails, and the user knows it.
  • Many users at the same time. No lock stops a user from opening a record. "Whereas Pessimistic Offline Lock assumes that the chance of session conflict is high and therefore limits the system's concurrency, Optimistic Offline Lock assumes that the chance of conflict is low."1
  • No lock management. There is no lock table, and no lock is left behind when a user closes the browser.
  • Simple to add. One column and one condition in each UPDATE and DELETE. Many tools do it for you.

Liabilities.

A save with no check loses data. In the following program, each session saves its whole copy of the record, and nothing checks what changed since the session read it.

This code runs but gives a wrong answer on purpose.

table = {1: {"name": "Acme Ltd", "credit": 500}}

# Two sessions read the same record, each in its own system transaction.
ann = dict(table[1])
bob = dict(table[1])

bob["credit"] = 800
table[1] = bob  # bob saves first

ann["name"] = "Acme Group"
table[1] = ann  # Wrong: ann's session saves its whole copy, with no check of what changed since it read the row

print("final:", table[1])
print("bob's credit change is lost:", table[1]["credit"] != 800)
Output
final: {'name': 'Acme Group', 'credit': 500}
bob's credit change is lost: True

Add a version to the record, keep it with each copy, and make the save fail when the version changed.

The conflict comes at the end. The user finds the conflict only when the work is done. About a business transaction with many conflicts, Rice writes that "the victims will do all the transaction work only to find at the last minute that the whole thing will fail and their time will have been wasted."2 When conflicts are frequent, a Pessimistic offline lock is better.

Every write must check. One UPDATE without the version condition opens the hole again. An Implicit lock puts the check in shared code, such as the mapper, so that no script can forget it.

Inconsistent reads. The check covers only the rows that the session saves. "Also, with one session editing data that another is reading an inconsistent read becomes likely."1 To check a row that the session only read, the save must also check the version of that row.3

When not to use it

When conflicts are frequent or costly. If many users edit the same records, or if a business transaction takes a long time, many users will lose their work at the end. Use a Pessimistic offline lock.

When one system transaction is enough. If the read and the write happen in one short request, the locks and the isolation of the database are enough.

When the change does not need the old copy. Some changes, such as a counter that many sessions increase, are better as one UPDATE that changes the value in the database, such as SET stock = stock - 1.

Version number or timestamp. The Jakarta Persistence specification describes optimistic locking as a system "where each revision of an item of data is assigned a version number or timestamp."4 A number is safer than a timestamp, because two saves can happen in the same tick of the clock.

Compare the old values. In place of a version, the WHERE clause can contain the old values of all the fields that the session read. This needs no new column, but the statements are longer.

Conditional requests in HTTP. An HTTP client can send If-Match with the entity tag that it read. RFC 9110 says that If-Match is used "to prevent accidental overwrites when multiple user agents might be acting in parallel on the same resource".5 The server refuses the request when the tag changed.

Related patterns. A Pessimistic offline lock prevents the conflict in place of finding it. A Coarse-grained lock puts one version on a group of objects, such as a customer and its addresses. An Implicit lock makes the shared code do the check. A Unit of Work or a Data Mapper is a good place for the checked UPDATE, and the Identity Field tells the save which row to check.

Known uses

  • Jakarta Persistence. "The persistence provider is required to perform optimistic locking automatically for every entity with a version".4 The version is a field with the @Version annotation, and a failed check throws an OptimisticLockException. The specification also warns that "Failure to make use of optimistic locking often leads to inconsistent entity state, lost updates, and other anomalies."4
  • Ruby on Rails. "Active Record supports optimistic locking if the lock_version field is present."6 A stale save raises ActiveRecord::StaleObjectError. To make the check work across web requests, "the recommended approach is to add lock_version as a hidden field to your form."6
  • HTTP servers that support If-Match with entity tags.5

References

  1. David Rice, Catalog of Patterns of Enterprise Application Architecture, Optimistic Offline Lock, pattern summary
  2. David Rice, Catalog of Patterns of Enterprise Application Architecture, Pessimistic Offline Lock, pattern summary
  3. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 16, Offline Concurrency Patterns, Optimistic Offline Lock
  4. Jakarta Persistence 3.2 specification, 3.5.1. Optimistic Locking
  5. RFC 9110, HTTP Semantics, June 2022, section 13.1.1 If-Match
  6. Ruby on Rails API, ActiveRecord::Locking::Optimistic, Usage

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/2A1PFZ/text.yaml