I want to abstract stats counting on objects within my system to a single place. At the moment each object increments a counter on its row in the MySQL table i.e. UPDATE sometable SET views = views + 1 WHERE id = ?
In order to get a significant performance gain instead of writing this update to the DB every time the object is used, I'd like to use apc to store a singleton analytics object in memory increment counters within this object and periodically save this object back to the DB.
However am I right in understanding that if two people visit the same page and increment the stats object it's possible that one of the views could be lost if they both do $obj->views = $obj->views + 1
because the stats object got from apc will have the same total view count, they both increment one and subsequently overwrite each other.
How do I get around this?
If you act in three steps :
Then, yes, you might have concurrency problems.
A better solution would be to have one APC entry for each one of your counters ; and use the apc_inc()
function to increment it.
It probably means having many entries (one per counter) -- but it also means that, in most sitautions (when incrementing the counters, which is what will be done the most), you won't have to care about concurrency : APC will deal with that for you.
Only problem that should remain is when you'll want to :
There, You might meet concurrency problems again.
Two solutions :
As a couple of sidenotes, now :
Memcache::increment
For the second point, your might want to switch to another solution, that would :