Programming Search⌘K

Patterncore

Pessimistic offline lock

Also called Pessimistic Offline Lock, pessimistic locking, check-out lock, lock-modify-unlock, reserved checkout.

A pessimistic offline lock makes a business transaction take a lock on the data before it uses the data, so only one business transaction at a time can edit it.

Family
architectural
Intent
Prevent conflicts between concurrent business transactions by allowing only one business transaction at a time to access data.

Intent

A pessimistic offline lock "Prevents conflicts between concurrent business transactions by allowing only one business transaction at a time to access data."1 A business transaction takes a lock on a record before it starts to edit the record, and keeps the lock until it ends.

Problem

A business transaction, such as the edit of a customer in a web form, often runs across many requests. One open system transaction of the database for the whole business transaction does not work well: "Sadly, however, this doesn't always work well because transaction systems aren't geared to work with long transactions."1 So the application uses many short system transactions, and it must control the concurrent access itself.

An Optimistic offline lock finds a conflict when a user saves. If conflicts are frequent, this is a bad experience. The user does all the work of the edit and finds only at the end that the save fails. A long edit, such as an insurance claim or a large order, can waste much time.

Solution

"Pessimistic Offline Lock prevents conflicts by avoiding them altogether."1 "It forces a business transaction to acquire a lock on a piece of data before it starts to use it, so that, most of the time, once you begin a business transaction you can be pretty sure you'll complete it without being bounced by concurrency control."1

The parts are:

  • The lock type. An exclusive write lock lets only one business transaction edit the record. An exclusive read lock also stops the others from reading it. A read/write lock lets many readers in, or one writer.2
  • The lock manager. One object that the application calls to acquire and to release the locks. It refuses a lock that another owner holds, and it does not wait, so a business transaction cannot wait for a lock forever.
  • The lock table. The locks must last across requests, and often across the processes of the application, so the lock manager keeps them in a table of the database. The resource is the primary key, so two sessions cannot both insert the same lock.
  • The owner. Usually the session or the business transaction. When it ends, the lock manager releases all its locks.
  • The timeout. A user can close the browser and never come back. The lock manager frees a lock that is older than a limit.
  time    session   call to the lock manager       lock table
  10:00   ann       acquire customer 1: granted    customer 1 -> ann
  10:05   bob       acquire customer 1: refused    customer 1 -> ann
  10:12   ann       release all                    (empty)
  10:15   bob       acquire customer 1: granted    customer 1 -> bob

In the following program, the check of the lock table and the take of the lock are one step, so only the first session gets the lock.

locks = {}  # resource -> owner; in a real application, a table in the database


def acquire(resource, owner):
    holder = locks.setdefault(resource, owner)  # one step: check and take
    return "granted" if holder == owner else f"refused, held by {holder}"


def release(resource, owner):
    if locks.get(resource) == owner:
        del locks[resource]


print("ann:", acquire("customer 1", "ann"))
print("bob:", acquire("customer 1", "bob"))
release("customer 1", "ann")
print("bob:", acquire("customer 1", "bob"))
Output
ann: granted
bob: refused, held by ann
bob: granted

Example

Each example file has a lock manager with a lock table. Each lock has a resource, an owner and the time when the owner took it, and the timeout is 30 minutes. Ann opens customer 1 for edit at 10:00 and gets the lock. Bob tries at 10:05 and is refused. Ann saves at 10:12, and that releases the lock of Ann. Bob then gets the locks on customer 1 and on order 9, but Bob closes the browser and does not come back. Carol is refused at 10:40, because the lock of Bob is 25 minutes old. At 10:50, the lock is 35 minutes old, so the lock manager deletes it, and Carol gets the lock.

PythonGitHub
import sqlite3

db = sqlite3.connect(":memory:")
db.execute("create table app_lock (resource text primary key, owner text, taken integer)")


class LockError(Exception):
    pass


# The lock manager keeps the locks in a table, so that they last across requests.
# The primary key makes the insert fail when another session holds the lock.
class LockManager:
    TIMEOUT = 30  # minutes: a lock that is older than this has been abandoned

    def acquire(self, resource, owner, now):
        with db:  # one system transaction for each step
            db.execute("delete from app_lock where resource = ? and taken <= ?", (resource, now - self.TIMEOUT))
            try:
                db.execute("insert into app_lock values (?, ?, ?)", (resource, owner, now))
            except sqlite3.IntegrityError:
                (holder,) = db.execute("select owner from app_lock where resource = ?", (resource,)).fetchone()
                if holder != owner:
                    raise LockError(f"{resource} is locked by {holder}") from None

    def release_all(self, owner):
        with db:
            db.execute("delete from app_lock where owner = ?", (owner,))


locks = LockManager()


def clock(minute):
    return f"10:{minute:02d}"


def open_for_edit(minute, who, resource):
    try:
        locks.acquire(resource, who, minute)
        print(f"{clock(minute)} {who} opens {resource} for edit: lock granted")
    except LockError as e:
        print(f"{clock(minute)} {who} opens {resource} for edit: refused: {e}")


def close(minute, who):
    locks.release_all(who)
    print(f"{clock(minute)} {who} saves and closes: locks released")


open_for_edit(0, "ann", "customer 1")
open_for_edit(5, "bob", "customer 1")
close(12, "ann")
open_for_edit(15, "bob", "customer 1")
open_for_edit(20, "bob", "order 9")
# Bob closes the browser and never comes back.
open_for_edit(40, "carol", "customer 1")
open_for_edit(50, "carol", "customer 1")
rows = db.execute("select resource, owner from app_lock order by resource").fetchall()
print("locks held:", ", ".join(f"{r} by {o}" for r, o in rows))
Output
10:00 ann opens customer 1 for edit: lock granted
10:05 bob opens customer 1 for edit: refused: customer 1 is locked by ann
10:12 ann saves and closes: locks released
10:15 bob opens customer 1 for edit: lock granted
10:20 bob opens order 9 for edit: lock granted
10:40 carol opens customer 1 for edit: refused: customer 1 is locked by bob
10:50 carol opens customer 1 for edit: lock granted
locks held: customer 1 by carol, order 9 by bob
  • Verdict: idiom. The lock table is a table in the database, so the locks last across requests and across the processes of the application. The primary key on resource makes the insert fail when another session holds the lock, so the check and the take are one step.
  • Each call of acquire first deletes a lock that is older than the timeout, in the same system transaction. This frees the locks of sessions that were abandoned.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

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

    record Lock(String owner, int taken) {}

    // The lock manager keeps the locks in a table, so that they last across requests.
    // In a real application, the table is in the database and the resource is its primary key.
    static class LockManager {
        static final int TIMEOUT = 30; // minutes: a lock that is older than this has been abandoned
        private final Map<String, Lock> table = new TreeMap<>();

        synchronized void acquire(String resource, String owner, int now) {
            table.computeIfPresent(resource, (r, lock) -> lock.taken() <= now - TIMEOUT ? null : lock);
            Lock holder = table.putIfAbsent(resource, new Lock(owner, now));
            if (holder != null && !holder.owner().equals(owner)) {
                throw new LockException(resource + " is locked by " + holder.owner());
            }
        }

        synchronized void releaseAll(String owner) {
            table.values().removeIf(lock -> lock.owner().equals(owner));
        }

        synchronized List<String> held() {
            List<String> out = new ArrayList<>();
            table.forEach((r, lock) -> out.add(r + " by " + lock.owner()));
            return out;
        }
    }

    static final LockManager locks = new LockManager();

    static String clock(int minute) { return String.format("10:%02d", minute); }

    static void openForEdit(int minute, String who, String resource) {
        try {
            locks.acquire(resource, who, minute);
            System.out.println(clock(minute) + " " + who + " opens " + resource + " for edit: lock granted");
        } catch (LockException e) {
            System.out.println(clock(minute) + " " + who + " opens " + resource + " for edit: refused: " + e.getMessage());
        }
    }

    static void close(int minute, String who) {
        locks.releaseAll(who);
        System.out.println(clock(minute) + " " + who + " saves and closes: locks released");
    }

    public static void main(String[] args) {
        openForEdit(0, "ann", "customer 1");
        openForEdit(5, "bob", "customer 1");
        close(12, "ann");
        openForEdit(15, "bob", "customer 1");
        openForEdit(20, "bob", "order 9");
        // Bob closes the browser and never comes back.
        openForEdit(40, "carol", "customer 1");
        openForEdit(50, "carol", "customer 1");
        System.out.println("locks held: " + String.join(", ", locks.held()));
    }
}
Output
10:00 ann opens customer 1 for edit: lock granted
10:05 bob opens customer 1 for edit: refused: customer 1 is locked by ann
10:12 ann saves and closes: locks released
10:15 bob opens customer 1 for edit: lock granted
10:20 bob opens order 9 for edit: lock granted
10:40 carol opens customer 1 for edit: refused: customer 1 is locked by bob
10:50 carol opens customer 1 for edit: lock granted
locks held: customer 1 by carol, order 9 by bob
  • Verdict: idiom. The methods of the lock manager are synchronized, and putIfAbsent checks and takes the lock in one call. computeIfPresent removes a lock that is older than the timeout.
  • The resource names are keys of a TreeMap, so held lists the locks in a stable order.
JavaScriptGitHub
class LockError extends Error {}

// The lock manager keeps the locks in a table, so that they last across requests.
// In a real application, the table is in the database and the resource is its primary key.
class LockManager {
  static TIMEOUT = 30; // minutes: a lock that is older than this has been abandoned
  #table = new Map(); // resource -> { owner, taken }

  acquire(resource, owner, now) {
    const lock = this.#table.get(resource);
    if (lock && lock.taken <= now - LockManager.TIMEOUT) this.#table.delete(resource);
    const holder = this.#table.get(resource);
    if (!holder) this.#table.set(resource, { owner, taken: now });
    else if (holder.owner !== owner) throw new LockError(`${resource} is locked by ${holder.owner}`);
  }

  releaseAll(owner) {
    for (const [resource, lock] of this.#table) if (lock.owner === owner) this.#table.delete(resource);
  }

  held() {
    return [...this.#table].sort(([a], [b]) => a.localeCompare(b)).map(([r, l]) => `${r} by ${l.owner}`);
  }
}

const locks = new LockManager();
const clock = (minute) => `10:${String(minute).padStart(2, "0")}`;

function openForEdit(minute, who, resource) {
  try {
    locks.acquire(resource, who, minute);
    console.log(`${clock(minute)} ${who} opens ${resource} for edit: lock granted`);
  } catch (e) {
    if (!(e instanceof LockError)) throw e;
    console.log(`${clock(minute)} ${who} opens ${resource} for edit: refused: ${e.message}`);
  }
}

function close(minute, who) {
  locks.releaseAll(who);
  console.log(`${clock(minute)} ${who} saves and closes: locks released`);
}

openForEdit(0, "ann", "customer 1");
openForEdit(5, "bob", "customer 1");
close(12, "ann");
openForEdit(15, "bob", "customer 1");
openForEdit(20, "bob", "order 9");
// Bob closes the browser and never comes back.
openForEdit(40, "carol", "customer 1");
openForEdit(50, "carol", "customer 1");
console.log("locks held:", locks.held().join(", "));
Output
10:00 ann opens customer 1 for edit: lock granted
10:05 bob opens customer 1 for edit: refused: customer 1 is locked by ann
10:12 ann saves and closes: locks released
10:15 bob opens customer 1 for edit: lock granted
10:20 bob opens order 9 for edit: lock granted
10:40 carol opens customer 1 for edit: refused: customer 1 is locked by bob
10:50 carol opens customer 1 for edit: lock granted
locks held: customer 1 by carol, order 9 by bob
  • Verdict: idiom. The lock table is a Map in a private field of the lock manager. acquire has no await between the check and the take, so no other code can run between the two steps. With a database, the lock table would have the resource as its primary key.
  • releaseAll removes all the locks of one owner when the business transaction ends, for example when the user saves or cancels.
package main

import (
	"fmt"
	"slices"
	"strings"
	"sync"
)

type lockError struct{ resource, holder string }

func (e *lockError) Error() string { return e.resource + " is locked by " + e.holder }

type lock struct {
	owner string
	taken int
}

// LockManager keeps the locks in a table, so that they last across requests.
// In a real application, the table is in the database and the resource is its primary key.
type LockManager struct {
	mu    sync.Mutex
	table map[string]lock
}

const timeout = 30 // minutes: a lock that is older than this has been abandoned

func (m *LockManager) Acquire(resource, owner string, now int) error {
	m.mu.Lock()
	defer m.mu.Unlock()
	if l, ok := m.table[resource]; ok && l.taken <= now-timeout {
		delete(m.table, resource)
	}
	l, ok := m.table[resource]
	if !ok {
		m.table[resource] = lock{owner, now}
		return nil
	}
	if l.owner != owner {
		return &lockError{resource, l.owner}
	}
	return nil
}

func (m *LockManager) ReleaseAll(owner string) {
	m.mu.Lock()
	defer m.mu.Unlock()
	for r, l := range m.table {
		if l.owner == owner {
			delete(m.table, r)
		}
	}
}

func (m *LockManager) Held() string {
	m.mu.Lock()
	defer m.mu.Unlock()
	var out []string
	for r, l := range m.table {
		out = append(out, r+" by "+l.owner)
	}
	slices.Sort(out)
	return strings.Join(out, ", ")
}

var locks = &LockManager{table: map[string]lock{}}

func clock(minute int) string { return fmt.Sprintf("10:%02d", minute) }

func openForEdit(minute int, who, resource string) {
	if err := locks.Acquire(resource, who, minute); err != nil {
		fmt.Printf("%s %s opens %s for edit: refused: %v\n", clock(minute), who, resource, err)
		return
	}
	fmt.Printf("%s %s opens %s for edit: lock granted\n", clock(minute), who, resource)
}

func closeEdit(minute int, who string) {
	locks.ReleaseAll(who)
	fmt.Printf("%s %s saves and closes: locks released\n", clock(minute), who)
}

func main() {
	openForEdit(0, "ann", "customer 1")
	openForEdit(5, "bob", "customer 1")
	closeEdit(12, "ann")
	openForEdit(15, "bob", "customer 1")
	openForEdit(20, "bob", "order 9")
	// Bob closes the browser and never comes back.
	openForEdit(40, "carol", "customer 1")
	openForEdit(50, "carol", "customer 1")
	fmt.Println("locks held:", locks.Held())
}
Output
10:00 ann opens customer 1 for edit: lock granted
10:05 bob opens customer 1 for edit: refused: customer 1 is locked by ann
10:12 ann saves and closes: locks released
10:15 bob opens customer 1 for edit: lock granted
10:20 bob opens order 9 for edit: lock granted
10:40 carol opens customer 1 for edit: refused: customer 1 is locked by bob
10:50 carol opens customer 1 for edit: lock granted
locks held: customer 1 by carol, order 9 by bob
  • Verdict: idiom. A sync.Mutex makes each method of the lock manager one step, because many goroutines can serve requests at the same time. lockError holds the resource and the holder for the message.
  • Held sorts the list, because the order of a range over a map is not defined.
RustGitHub
use std::collections::BTreeMap;

struct Lock {
    owner: String,
    taken: u32,
}

// The lock manager keeps the locks in a table, so that they last across requests.
// In a real application, the table is in the database and the resource is its primary key.
struct LockManager {
    table: BTreeMap<String, Lock>,
}

const TIMEOUT: u32 = 30; // minutes: a lock that is older than this has been abandoned

impl LockManager {
    fn acquire(&mut self, resource: &str, owner: &str, now: u32) -> Result<(), String> {
        if let Some(l) = self.table.get(resource) {
            if l.taken + TIMEOUT <= now {
                self.table.remove(resource);
            }
        }
        match self.table.get(resource) {
            None => {
                self.table.insert(resource.to_string(), Lock { owner: owner.to_string(), taken: now });
                Ok(())
            }
            Some(l) if l.owner != owner => Err(format!("{} is locked by {}", resource, l.owner)),
            Some(_) => Ok(()),
        }
    }

    fn release_all(&mut self, owner: &str) {
        self.table.retain(|_, l| l.owner != owner);
    }

    fn held(&self) -> String {
        let v: Vec<String> = self.table.iter().map(|(r, l)| format!("{} by {}", r, l.owner)).collect();
        v.join(", ")
    }
}

fn clock(minute: u32) -> String {
    format!("10:{:02}", minute)
}

fn open_for_edit(locks: &mut LockManager, minute: u32, who: &str, resource: &str) {
    match locks.acquire(resource, who, minute) {
        Ok(()) => println!("{} {} opens {} for edit: lock granted", clock(minute), who, resource),
        Err(e) => println!("{} {} opens {} for edit: refused: {}", clock(minute), who, resource, e),
    }
}

fn close(locks: &mut LockManager, minute: u32, who: &str) {
    locks.release_all(who);
    println!("{} {} saves and closes: locks released", clock(minute), who);
}

fn main() {
    let mut locks = LockManager { table: BTreeMap::new() };
    open_for_edit(&mut locks, 0, "ann", "customer 1");
    open_for_edit(&mut locks, 5, "bob", "customer 1");
    close(&mut locks, 12, "ann");
    open_for_edit(&mut locks, 15, "bob", "customer 1");
    open_for_edit(&mut locks, 20, "bob", "order 9");
    // Bob closes the browser and never comes back.
    open_for_edit(&mut locks, 40, "carol", "customer 1");
    open_for_edit(&mut locks, 50, "carol", "customer 1");
    println!("locks held: {}", locks.held());
}
Output
10:00 ann opens customer 1 for edit: lock granted
10:05 bob opens customer 1 for edit: refused: customer 1 is locked by ann
10:12 ann saves and closes: locks released
10:15 bob opens customer 1 for edit: lock granted
10:20 bob opens order 9 for edit: lock granted
10:40 carol opens customer 1 for edit: refused: customer 1 is locked by bob
10:50 carol opens customer 1 for edit: lock granted
locks held: customer 1 by carol, order 9 by bob
  • Verdict: idiom. acquire and release_all take &mut self, so the compiler allows no other access to the table while they run. A server with threads would put the lock manager in a Mutex.
  • release_all uses retain to keep only the locks of the other owners.

Consequences

Benefits.

  • No lost work. A user who has the lock can finish the edit, and the save does not fail because of another session.
  • Early refusal. A user who cannot get the lock knows it at the start, before any work is done.
  • Simple saves. The save does not need a version check for the data that the lock covers.

Liabilities.

The check and the take must be one step. If the lock manager first checks that a lock is free and then takes it in a later step, two sessions can both see the lock as free. In the following program, both sessions think that they hold the lock.

This code runs but gives a wrong answer on purpose.

locks = {}


def is_free(resource):  # step 1, in one system transaction
    return resource not in locks


def take(resource, owner):  # step 2, in a later system transaction
    locks[resource] = owner


# Wrong: the check and the take are two steps, and two sessions run them at the same time.
ann_sees_free = is_free("customer 1")
bob_sees_free = is_free("customer 1")
if ann_sees_free:
    take("customer 1", "ann")
if bob_sees_free:
    take("customer 1", "bob")

print("ann's session thinks it holds the lock:", ann_sees_free)
print("bob's session thinks it holds the lock:", bob_sees_free)
print("the lock table says:", locks["customer 1"])
Output
ann's session thinks it holds the lock: True
bob's session thinks it holds the lock: True
the lock table says: bob

Make the take one atomic step, such as an insert into a table with the resource as its primary key, or one setdefault on a shared map that a single process owns.

Less concurrency. Only one user at a time can edit a record. If the users often edit the same data, they must wait for each other.

Abandoned locks. A user can leave a lock in place for hours. A timeout frees it, but the timeout is a balance: a short timeout takes the lock from a slow user, and a long timeout keeps the others out. WebDAV has the same problem, and RFC 4918 says that "A lock MAY have a limited lifetime."3

Lock management. The application must know the owner of each lock, release the locks at the end of each business transaction, and give the users a way to see and to break the locks.

Deadlock. If a business transaction waits for a lock, two of them can each wait for a lock that the other holds. A lock manager that refuses at once, and does not wait, avoids this Deadlock.2

When not to use it

When conflicts are rare. An Optimistic offline lock gives more concurrency and needs no lock table. Rice suggests trying it first, and using the pessimistic lock when the conflicts of the optimistic lock cost too much.1

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

When the users cannot be trusted to release the locks. Public applications, where many users open records and leave, fill the lock table with abandoned locks.

Shared and exclusive locks. RFC 4918 for WebDAV has exclusive locks and shared locks: "The most basic form of lock is an exclusive lock."3 "A shared lock allows multiple principals to receive a lock."3 A Read-write lock is the same idea inside one process.

Database row locks. A database can lock a row in one system transaction with SELECT ... FOR UPDATE. In Rails, "Locking::Pessimistic provides support for row-level locking using SELECT … FOR UPDATE and other lock types."4 Such a lock ends with the system transaction, so it is not an offline lock. It is useful for the short step that takes an offline lock.

Related patterns. An Optimistic offline lock finds conflicts in place of preventing them. A Coarse-grained lock takes one lock for a group of objects. An Implicit lock makes the shared code take the locks, so that no script forgets one. Inside one process, the same idea is Mutual exclusion.

Known uses

  • WebDAV. The LOCK method of RFC 4918 gives a client a write lock on a resource. The RFC describes locking as the ability to "keep more than one person from working on a document at the same time", which prevents lost updates.3 Each lock has a timeout: "Timeout is measured in seconds remaining until lock expiration."3
  • Subversion. The svn lock command gives the lock-modify-unlock model for files that cannot be merged, such as images. "Subversion's locking feature exists ultimately to minimize wasted time and effort."5 It works "By allowing a user to programmatically claim the exclusive right to change a file in the repository".5 The locks can be broken: "in Subversion's default configuration state, locks can be released not only by the person who created them, but by anyone."5
  • File locks of the operating system, such as the locks of Lock a file, which keep one writer on a file.

References

  1. David Rice, Catalog of Patterns of Enterprise Application Architecture, Pessimistic Offline Lock, pattern summary
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 16, Offline Concurrency Patterns, Pessimistic Offline Lock
  3. RFC 4918, HTTP Extensions for Web Distributed Authoring and Versioning (WebDAV), June 2007, section 1 Introduction; section 6.2 Exclusive vs. Shared Locks; section 6.6 Lock Timeout
  4. Ruby on Rails API, ActiveRecord::Locking::Pessimistic, description
  5. Version Control with Subversion, for Subversion 1.7, Locking, introduction; Breaking and Stealing Locks

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/92KTZK/text.yaml