Re:PostgreSQL anti-patterns: read-modify-write cycles (2014)
by dalore on Wednesday December 21, 2016 @10:18AM
(#13229745)
Another solution would be to have a view that calculates the balance from the transactions.
Then your sql code can check the balance without doing a sum (which might get expensive, and often the same value until a transaction changes it) just by joining to that view.
i.e. `WHERE total_view.balance > 0`
1) you make transactions serialized
2) or you use row level locking on an additional table (say user, while this conflicts with the system table user, but for the sake of the example we assume this is not the case) to serialize the access. Now it may be tempting to change this to Just for clarity: in most cases you should register your transaction event anyway (with a time stamp) for later auditing, but you now will have a risk of introducing inconsistencies between calculated balance and transactions due to the programming errors (that is partially committed transactions).Also you should obviously create proper primary keys and indexes.
Also you should include proper error/exception handling.
Also if you already do locking, then you could also consider different locking strategies described in the article.