Bloqueo Optimista
Control de concurrencia optimista
Escrito por Darjus Kazakevic · revisado el
Let both writers proceed, then reject the one that read old data.
Two users open the same order and both press Save. Without any check, the second write wins and the first change disappears with no error. This is the lost update problem, and it is the default behavior of a naive read-modify-write.
Optimistic locking assumes conflicts are rare, so nothing is locked. Each row has a version column. Every update says WHERE version = <the one I read> and increments it. If the update matches zero rows, someone else committed first, and you get a conflict error instead of a silent overwrite.
En esencia — Store a version on each row and check it in the UPDATE; a write that matches zero rows read stale data and is rejected, not applied.
Cuándo recurrir a él
Recurre a él cuando
- Conflicts on the same row are rare
- A user edits a form for minutes before saving
- Any read-modify-write where a lost update would be silent
Reconsidéralo cuando
- Hot rows where most writers would lose and retry
- Work that cannot be retried or shown to a user as a conflict
- Single-writer queues where nothing competes
The mechanics
- The version
- A number stored with the row, read with it, and increased by every write. The update sends back the version it read, and the database checks it in the same statement.
- The conflict
- An update that matches zero rows means someone else committed first. Treat it as a normal outcome with a named error, not as a crash.
- The resolution policy
- What to do after a conflict is a product decision. A background job can re-read and retry. A user who edited a form should see the newer data, not have their input replayed.
Applying it well
- Put the version check inside the UPDATE
- Check and write in one statement: UPDATE … WHERE id = ? AND version = ?. A separate SELECT then UPDATE leaves a gap where another writer can commit in between.
- Version the aggregate root
- Increase the root's version when any part of the aggregate changes. Then two writers that touch different lines of one order still conflict, which protects the order's rules.
- Choose the retry policy per use case
- Retry automatically only when re-running is safe, and cap it. For a form a user edited, show the newer data instead of replaying their input over it.
- Switch to pessimistic for hot rows
- If most writers on one row lose and retry, as with a shared counter or one stock record, optimistic locking wastes work. Lock the row first, or split it into several rows.
Errores habituales
- Versioning child rows instead of the aggregate root, so the aggregate's rules are not protected.
- Retrying a step that is not idempotent, such as sending an email, and doing it twice.
- Retrying without a limit, which multiplies load exactly when the system is busy.
- Checking the version in a SELECT before the UPDATE, which leaves a gap and protects nothing.