DEV Community

Manjunath Reddy
Manjunath Reddy

Posted on • Updated on

REST API: How to avoid duplicate resource creation on concurrent requests

Liquid syntax error: Unknown tag 'endraw'

Top comments (4)

Collapse
 
erescobar profile image
erescobar

Hi and thanks for this article. I have a small question, in the method 2 you use check if the payment exists in-memory but why not to just store the payment in-memory and handle the exception

// make a unique reference key for each payment transaction
var paymentKey = 'PAYMENT' + user_id + order_id

try {
   setPayment(paymentKey);
} catch(Error e) {
  // check duplicated error 
  print 'Payment already exists!. Must be duplicate payment'
  throw Error('duplicate') or return;
}

var newPayment = createPayment(userId, reqParams)
Enter fullscreen mode Exit fullscreen mode
Collapse
 
manjufy profile image
Manjunath Reddy

Hey, you could store the payment in in-memory, however, if you are application is scaled across multiple nodes, that method makes it hard to avoid duplicate constraint. Let me know whats your thoughts if you could elaborate more about your approach.

Collapse
 
alvin30595 profile image
Alvin Lai

Hi, thanks for the explanation above. However, may i know does your backend use Node instead of PHP, as i did experience use method 4 with PHP will still face the issue due to slow read/write of mysql?

Collapse
 
manjufy profile image
Manjunath Reddy

My Backend was Node.
However, if the read/write is slow, with method 4, you are guaranteed that there will not be a duplicate due to DB constraint policy.