0

I have an article model, and a comment model. Each article can have up to 10 comments.

Whenever I add a comment, this check is done in the controller.

Article.findOne({ id: 3 }, function(err, record){

    if(record.commentCount < 10){

        Comment.create({ /* parameters */ })    

    }    

});

(the code isn't checked, but the important part is that there are two queries here).

Now, since Node.js is run in several threads on several computers, this will definitely result in race condition. If 100 requests are done simultaneously, it's unavoidable that sometime some of them will get the count first simultaneously, and then add the comment because all of them thought that there are less than 10 comments.

How can I fix this? Is there a way to lock the database, or lock a row? Ruby on Rails allows me to do pessimistic locking and fix this problem perfectly.

1
  • You either need an atomic operation (on the database server) that adds a new comment only if there are less than 10 (SQL often used for things like that) or you need the ability for one process to acquire a temporary lock. Because both of these are database features that some will have and others will not, you need to be asking a question about a specific database. Your question as it stands now doesn't say anything about which database you are using or ask which database you should be using to get the right features. Commented Jul 5, 2017 at 5:44

1 Answer 1

3

if you use Sequelize as ORM; maybe you can use Transcation;

such as:

sequelize.transcation({
  isolationLevel: Sequelize.Transaction.ISOLATION_LEVELS.SERIALIZABLE
}, function(t){
  return Article.findOne({ id: 3, lock: t.LOCK.UPDATE }, function(err, record){
    if(record.commentCount < 10){
        Comment.create({ /* parameters */ })    
    }    
  });
})

Sequelize Doc

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.