Sobes.tech
Middle

Task with concurrent board update: how to solve the problem of lost updates (Lost Update) using database tools?

sobes.tech AI

Answer from AI

The Lost Update problem occurs when two or more processes read and update the same data simultaneously, and one update overwrites another, losing changes.

Database solutions include:

  1. Optimistic Locking

    • Add a version field to the table (e.g., version or updated_at).
    • When updating, check that the version has not changed since reading.
    • If the version has changed, reject the update and retry the operation.

    Example in SQL:

    UPDATE board
    SET content = :new_content, version = version + 1
    WHERE id = :board_id AND version = :old_version;
    
  2. Pessimistic Locking

    • Use SQL queries with locks, such as SELECT ... FOR UPDATE.
    • When reading a row, lock it for other transactions until the current one finishes.
  3. Transactions with SERIALIZABLE isolation level

    • Ensures sequential execution of transactions.
    • May lead to locking and reduced performance.

Optimistic locking is often preferred for web applications with high contention and low conflict probability, as it is more scalable and locks resources less.