title: How to prevent race condition when creating a document on parse server?
body: <p>A mobile app uses parse server as a backend with <code>mongoDB</code> as database.</p>
  
  <p>For every user in the <code>User</code> collection there is a user profile in the <code>UserProfile</code> collection. A user profile has a pointer field as a reference to the <code>User</code> to which the user profile belongs.</p>
  
  <p>The problem is that multiple user profiles are created for the same user during sign up.</p>
  
  <p>That is because the sign-up process looks like this:</p>
  
  <ol>
  <li><strong>Client:</strong> user signs up</li>
  <li><strong>Server:</strong> creates user profile in <code>afterSave</code> of <code>User</code></li>
  <li><strong>Client:</strong> after sign-up calls cloud code function <code>updateProfile</code> to update information in the user profile </li>
  <li><strong>Server:</strong> <code>updateProfile</code> looks for existing user profile or creates a new one if none exists</li>
  </ol>
  
  <p>This causes a race condition: The server creates a user profile in step #2 and at the same time <code>updateProfile</code> creates a new user profile in step #4. The time difference in <code>createdAt</code> of these user profiles is milliseconds.</p>
  
  <p>Now: </p>
  
  <ul>
  <li><p>If I leave out step #2, then even if step #4 gets calls multiple times immediately after each other, it can cause a race condition because <code>updateProfile</code> won't find a user profile until it's created. On the other hand every user needs to have a user profile associated with it, so creating it server side is the only way to ensure that.</p></li>
  <li><p>If I change step #4, to not create a new profile, then the information in the profile is not updated when the client calls the cloud code function <code>updateProfile</code> because the user profile from step #1 is not yet created.</p></li>
  </ul>
  
  <p>What is the correct approach?</p>
  
  <h2>Update:</h2>
  
  <ul>
  <li>Unfortunately the user profile cannot be created on <code>beforeSave</code> of the <code>User</code> because it doesn't seem to have an <code>ID</code> yet. If that was possible then it would be ensured that a user profile is created <em>before</em> the client calls <code>updateProfile</code>.</li>
  </ul>