skip to Main Content

Let say this is my API:

app.post('/refund', function (req, res) {
        Transaction.findOneAndUpdate({_id: req.body.transaction_id}, {$set: {refund_status: true}}).
        exec(function (err, transaction_status) {
            res.end("Refund successfully")
        }
}

If two admins click the refund button at the same time. My customer will receive a double refund.

So, how to prevent these issues?

2

Answers


  1. Simply get the transaction first and check the refund status and update. If its false refund. If its true tell its already refunded.

      app.post('/refund', function (req, res) {
        // get the transaction first
        Transaction.find({_id: req.body.transaction_id}, function(err, doc) {
          if (doc.refund_status == false) {
             Transaction.findOneAndUpdate({_id: req.body.transaction_id}, {$set: {refund_status: true}}).exec(function(err, transaction_status) {
               res.end("Refund successfully")
          })
          } else { // already refunded
            res.end("Already refunded")
          }
         })
      }
    
    Login or Signup to reply.
  2. Implement your refund logic in a callback from session.withTransaction(). That will prevent concurrent updates. Don’t worry about the async stuff; .withTransaction() handles it correctly.

    Or, make your refund logic idempotent. That is, implement it in a way that calling it multiple times does exactly the same thing as calling it once. Your setup is almost idempotent as it is: you start with the transaction id and set its refund statuse to true. But the idempotence may not work for you if you must report when the transaction is already refunded.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search