Skip to content
Discussion options

You must be logged in to vote

You’re facing a classic lost update problem. Here are three reliable solutions, ordered from simplest to most flexible

  1. Optimistic locking with a version column
    Add an integer version column to the users table. When updating, check that the version hasn’t changed:
UPDATE users 
SET balance = balance + 20, version = version + 1
WHERE id = ? AND version = ?;

If the row count is 0, retry the whole operation (read new balance, recalculate, update).
Works well when conflicts are rare. No explicit locks, good for read‑heavy workloads

  1. Use a row‑level SELECT FOR UPDATE
    Wrap the operation in a transaction and lock only the affected row:
BEGIN;
SELECT balance FROM users WHERE id = ? FOR UPDATE;
--

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@jutolin
Comment options

Answer selected by dimaashiftiing
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Code Search and Navigation Search, navigate, and understand code on GitHub Question Ask and answer questions about GitHub features and usage Welcome 🎉 Used to greet and highlight first-time discussion participants. Welcome to the community! source:ui Discussions created via Community GitHub templates Other Features and Feedback Discussions that fall into "Other" category
3 participants