Doing work in the web/backend server vs database server

Hey there! I’m a bit of a noob here, so I apologize in advance if the question is duplicated

What is the criteria for executing logic in the backend server vs doing it in the mongo server?
For example (sorry if the syntax is messed up):

You have user that has withdrawn some funds. To update their data you can either

const withdrawFunds = (userId, amount) => {
  const user = User.getById(userId)

  // option 1: Logic is executed by the backend server
  const currentFunds = user.funds - amount
  User.updateOne({_id: userId}, {$set: {funds: amount}})

  // option 2: Logic is executed by the mongo server
 User.updateOne({_id: userId}, {$set: {funds: { $inc: -amount}} )

Is one option generally more performant than the other, or does it depend on the servers being used?
Are there any rules of thumb for these types of situations?

The problem with option 1 is that you may end up with the wrong value for funds if withdrawFunds is called multiple time.

time 1, user.funds == X in first call
time 2, user.funds == X in second call
time 3, first call update user.funds with value X - amount_in_call_1
time 4, second call update user.funds with value X - amount_in_call_2
user.funds is not wrong because 2 withdrawals happen at the same time so the
new value should be X - amount_in_all_1 - amount_in_call_2
but it is X - amount_in_call_2

One round trip to the server is the only way to go.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.