jiminssy jiminssy - 2 years ago 151
Node.js Question

Concurrent control for NodeJS and MongoDB stack

I have these "tasks" that are submitted by users which hits my NodeJS server and stored as documents in MongoDB database. These tasks are then also fetched by users and worked on one at a time.

  • Tasks have states: Pending, Working, Completed

  • Initially when tasks are submitted, they are in "Pending" state.

  • When a user wants to work on a task they query one "Pending" task in FIFO fashion.

  • Upon giving a task to a user, that task is updated to have the state "Working"

My problem is when two users simultaneously ask for a task to work on, they might get the same task due to race condition. While the first query tries to update the task's state to "Working" second query can fetch that one as well. Could someone suggest me how I might be able to solve this using NodeJS and MongoDB where everything is asynchronous? Any frameworks or libraries are also welcomed too.

Answer Source

MongoDB has a findAndModify method exactly for that purpose.

Using the MongoDB driver, you would run the following code,

  // Query
}, [
  // Sort
], {
  $set: {
    state: 'working'
}, {
  new: true
}).then((task) => {
  // This is your "working" task
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download