title: How to prevent race conditions in a distributed nodejs web servers architecture backed by mongodb
body: <p>Here' s the description of my problem:</p>
  
  <ol>
  <li>I have x web workers written in nodejs (express.js) behind a load ballancer. These workers write data into mongodb (mongoose.js)</li>
  <li>I've setup endpoint y such that at some point in the middleware chain of the handler I'm doing the following logic: If the requesting user exists in the database, then fetch it, update some fields then store it back. If it doesn't exist, insert it in mongo.</li>
  </ol>
  
  <p>NOTE! I'm unable to use Mongoose's findAndUpdateOne() - which would be atomic - due to domain specific logic, ie. if the user already exists update it with a certain value, else insert it with another value.</p>
  
  <ol>
  <li>The problem is, quite often, two requests from the same user (who doesn't yet exist in the db) will hit two different workers. When user processing middleware kicks in, both workers will determine that the user doesn't exist and attempt to insert it then update it. Naturally this causes errors, eg. validation errors: I've setup a unique email per user validation and others.</li>
  </ol>
  
  <p>How can I prevent this?</p>