Question

I have a question about counterCache that the documentation doesn't clarify at all. Does counterCache checks race conditions when updating the field value?

For example, let's say we have a forum implementation, and for each forum, we have a number n of topics stored via counterCache. Then, if two users use the model at almost same time (enough to overlap their operations, meaning that when one ends it, the other one still will be using it), and one create a new topic and the other one (assuming it can) deletes another topic, then will it show exactly n topics, and not n+1 or n-1?

Was it helpful?

Solution

Whatever operation finishes first will be the result. It is very unlikely and probably technically impossible that the operation happen at the same time. So one of both comes first. Then there is also the time it takes for the request to be received by the server and browser. So whenever the next view request comes you'll get whatever at this point was updated in the database.

By checking the code you can also see that the code is doing a find('count') instead of inc/decrementing by +/- one. http://api.cakephp.org/2.3/source-class-Model.html#1913-1981 So the cache gets written after the previous action was completed.

And finally I would really not worry about if the count is off by +/- one for a moment, specially in a forum.

OTHER TIPS

I believe it could, but not because of Cake but because multiple SQL operations in a non transactional behaviour, and from multiple clients (users) at the same time. Any web application with or without a framework would suffer from this situations.

I'm not very proficient with SQL transactions, but I'm pretty sure some kind of transaction configuration would prevent this form happening.

As burzum says, the forum example is definitely not something to worry about.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top