Say you have an Action in ASP.NET MVC in a multi-instance environment that looks something like this*:
public void AddLolCat(int userId)
{
var user = _Db.Users.ById(userId);
user.LolCats.Add( new LolCat() );
user.LolCatCount = user.LolCats.Count();
_Db.SaveChanges();
}
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.
Question
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.
- I guess you have to make some kind of a network based lock?
- Do you really have to suffer the extra latency per call?
- Can you tell an Action that it is only allowed to be executed once per User?
- Is there any common pattern already in place that you can use? Like a Filter or attribute?
- Do you return early, or do you really lock the process?
- When you return early, is there an 'established' response / response code I should return?
- When you use a lock, how do you prevent thread starvation with (semi) long running processes?
* just a stupid example shown for brevity. Real world examples are a lot more complicated.