asp.net mvc - How to avoid Race Conditions when a restful architecture doesn't make sense -


i'm making website don't think makes sense implement restful architecture (at least not portion relevant problem), it's causing problems race conditions across multiple servers share database.

my website has info users of product, has users table (not users of site though). users have many files.

users , files populated automated service, not manually on site. service posts files server, server parses them , gets username file. if username new, creates new user row in table. returns file service made request.

the problems i'm seeing when race conditions when multiple requests come in @ same time related objects, , causes things violations of unique indexes in db.

for example, there unique key on username. code can problem if 2 requests automated service files same user come in @ same time.

var myuser = db.users.firstordefault(u => u.username == username); if(myuser == null) {    myuser = new user(username);    db.addobject(user); } db.savechanges(); 

request 1 see there no user username foo, if condition returns true. request 2 sees same thing, not knowing request 1 began creating user, , when request 2 tries save, violates unique key.

is there common pattern or solution problem? know wouldn't problem if server restful, don't think it's feasible service change way makes requests, i'd stay same if possible. right now, posts file server, not knowing whether user of file existed already, or whether file posted server yet (it may post more once). objects created if don't exist yet, , if do, list of items updated. far service concerned, wants know info file, , isn't concerned whether or not exists in db.

i think it'd slow try create user via request, try create file via request, , request info file in request. also, service runs multiple requests @ time via parallel.foreach, , it'd slow run in single thread.

the first thing separation of concerns. if have automated service populating data, that service (or piece of middleware) should responsible creating database records. shouldn't happen @ run time in response request website.

second, if must way, locks for. each request website runs in it's own thread(s). so, if multiple threads need access same volatile resource (your db) need institute optimistic locking, first thread in wins , further threads able try interact table or row (depending on type of lock) once first has completed work.

third, pretty exactly restful architecture attempts solve. can use etags version resources attempt post outdated resource return http error (409 conflict) directing client refetch original resource.


Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -