title: Best way to prevent race conditions in a multi instance web environment?
body: <p>Say you have an Action in ASP.NET MVC in a multi-instance environment that looks something like this*: </p>
  
  <pre><code>public void AddLolCat(int userId)
  {
      var user = _Db.Users.ById(userId);
  
      user.LolCats.Add( new LolCat() );
  
      user.LolCatCount = user.LolCats.Count();
  
      _Db.SaveChanges();
  }
  </code></pre>
  
  <p>When a user repeatedly presses a button or refreshes, race conditions will occur, making it possible that LolCatCount is not similar to the amount of LolCats. </p>
  
  <p><strong>Question</strong></p>
  
  <p>What is the common way to fix these issues? You could fix it client side in JavaScript, but that might not always be possible. I.e. when something happens on a page refresh, or because someone is screwing around in Fiddler. </p>
  
  <ul>
  <li>I guess you have to make some kind of a network based lock? </li>
  <li>Do you really have to suffer the extra latency per call?</li>
  <li>Can you tell an Action that it is only allowed to be executed once per User? </li>
  <li>Is there any common pattern already in place that you can use? Like a Filter or attribute?</li>
  <li>Do you return early, or do you really lock the process?</li>
  <li>When you return early, is there an 'established' response / response code I should return?</li>
  <li>When you use a lock, how do you prevent thread starvation with (semi) long running processes?</li>
  </ul>
  
  <p>* just a stupid example shown for brevity. Real world examples are a lot more complicated.</p>