I want to atomically update a record to maintain consistency, it could be done easily with the following SQL.
UPDATE account SET balance = balance - 25 WHERE id = '5' AND balance > 25
or NoSQL (MongoDB)
db.account.update({_id: 5, balance: {$gte: 5}}, {$inc: {balance: -5}})
But in DDD, how can I do this properly without a race condition problem? This should be fast so explicit lock should be avoided. (Unless unavoidable for the sake of DDD.)
Race condition may occur
class ApplicationService
func creditAccount(String accountId, int amount)
let account = accountRepository.find(accountId)
account.credit(amount)
accountRepository.save(account)
Double dispatch?
class ApplicationService
func creditAccount(String accountId, int amount)
let account = accountRepository.find(accountId)
account.credit(amount, accountDao)
class Account
func credit(int amount, AccountDao dao)
this.balance = dao.adjustAmountAndReturn(this.id, -amount)
EDIT
I know that the risk of race condition is low but the damage is high, thus probability multiply by cost still results high expected value.
In this question, I'm looking for a solution that fits both RDBMS and NoSQL.