Sobes.tech
Senior

What is optimistic locking?

sobes.tech AI

Answer from AI

Optimistic locking is a concurrency control strategy where conflicts during simultaneous data modifications are assumed to be rare.

Instead of locking the resource during an operation (as in pessimistic locking), optimistic locking allows multiple transactions to work in parallel, checking for conflicts when changes are saved.

The main mechanism is storing a version or checksum of the data. When updating, it checks that the data version has not changed since it was read. If it has changed, it means another process has modified the data, and the current operation is rolled back or retried.

Example of usage:

  • In a database, a table has a 'version' field (number).
  • A client reads a record with version=1.
  • The client tries to update the record, specifying WHERE version=1.
  • If the version in the database has already become 2, the update will not be executed, and the client will be notified of a conflict.

Optimistic locking is suitable for systems with low contention and high load, where locks can significantly reduce performance.

Example in Go (simplified):

 type Record struct {
    ID      int
    Data    string
    Version int
}

func UpdateRecord(r *Record, newData string) error {
    // Read current version from DB
    currentVersion := getVersionFromDB(r.ID)
    if currentVersion != r.Version {
        return errors.New("update conflict")
    }
    // Update data and increment version
    r.Data = newData
    r.Version++
    // Attempt to save with version condition
    err := updateInDB(r)
    if err != nil {
        return err
    }
    return nil
}

Thus, optimistic locking helps avoid locks and ensures data integrity during concurrent modifications.

What is optimistic locking? — Golang - sobes.tech