Multiple instances adding to the same attribute.

Michael Chow wrote:

Is there a possibility, when for example, counting a certain request, that a highly coincidental retrieval of information by two clients will override eachother's contributions? Suppose you have:

counter +=1

If another request gets the initial counter value before the first one had time to save, and then the first one saves, then the second one saves, the counter is only updated by 1 instead of 2.

Does rails somehow protect itself from this kind of possibility? To be honest I'm not particularly familiar with server side applications, do they run in parallel or do they always finish processing the first request before serving the next?

A Rails process currently serializes requests, so there is no problem unless you run multiple Rails processes to increase server capacity.

But this is done very commonly, so you should allow for concurrency by instead writing counter updates directly to the database:

    model = Model.find(:first)     Model.increment_counter(:counter,

Michael Chow wrote:

Would model.update_attribute(:counter, model.counter+1) maintain the same concurrency as your increment_counter class method? Wouldn't the increment_counter method itself implement update_attribute?


update_attribute uses the in-memory Ruby counter value, which may be stale.

increment_counter reads and increments the database value.

update_attribute can however be safe if you've obtained the right table locks.