Thursday, 11 May 2017

Node.js avoid db race condition with cluster/pm2

Lets assume we have a node js application which runs in cluster mode/pm2.

Lets assume we have a function which checks if a specific row is in a db table and (if not) creates it. If its already available a value is set and saved.

We only want one row for each combination of userId and groupId.

function someFunction()={
  return Activation.findOne({ where: { userId: userId, groupId: groupId } })
                    .then(activationObject => {

                        if (!activationObject) {
                            return Activation.create({ userId: userId, groupId: groupId, activationTime: sequelize.fn('NOW') })
                        } else {
                            activationObject.activationTime = sequelize.fn('NOW');
                            return activationObject.save()
                        }

                    })

}

How can we avoid race condition when running node in cluster mode (Worker One Checks if Row is available and Worker 2 checks at the same time. Both get no result and in the end we have to newly created rows instead of one)?

(Yes, I know that sequelize provides a findOrCreate() method but I wanted an easy understandable example)



via Andybanandy

No comments:

Post a Comment