Caching COUNT with PHP and Redis
forrst.com
forrst.com
Warning, this is a myth: once you starte relying on caching to serve your amount of traffic, flushing the cache will have the result of taking the site down. This is why persistence is an absolute requirement of a serious caching server IMHO. With Redis when things may be in desync it's better to selectively remove entries with (RANDOMKEY+DEL) at a rate that the system is able to handle.
Also given that you are using Redis that has atomic increments, why not going the extra mile and issuing INCR/DECR operations when something is added/removed?
Useful tip about randomkey and del, thank you.
I def. could switch it over to an incr/decr setup. Maybe I'll do that tonight.
And perhaps MemcacheDB (http://memcachedb.org/) is a better bet if you don’t need Redis’s list and set operations. But I don’t understand why the cache needs to be persistent.
1. This is a better fit for memcache than redis, since you can get the counts to expire automatically
2. If you are fetching paginated results with a LIMIT (and you usually are) then you can use the SQL_CALC_FOUND_ROWS prefix on your SELECT to get these counts for "free" from MySQL without needing to do your own caching (see http://dev.mysql.com/doc/refman/5.0/en/select.html )
You can also do a grouped count query in a single query, by using something like:
SELECT COUNT(*) FROM comments WHERE GROUP BY post_id;
From that he gets an array of all the counts, so he can look those up easily.
And that result can also be cached as well, of course.
On innodb, because of transactions, this is not possible, and it needs to actually count the rows.
BUT, the query itself is still cached - at least until the underlying table gets updated, which invalidates the cache (I'm not sure of the exact invalidation strategy, but it's part of MySQL and doesn't depend on the engine).