I’m looking for a real-time counter that updates as more database entries (sales) are created (for example, http://www.humblebundle.com). I’m trying not to put unnecessary strain on the database.
A naive way to do this would just be to ping the database for the sales count every second or so and update the number in real-time with javascript. This’ll put way too much strain on the database and is unworkable, but that’s the basic effect I’m trying to achieve.
Another way I can think of is to somehow store the sales number in a cache instead of the database, and then adding +1 to this cache every time a sale is made. The counter then gets updated every second with the new value of the cached count. This seems like it might work a lot better, but I don’t know specifically how to implement this in Rails.
I’m using Rails 3.1 and jQuery on Heroku, but I’m mostly just looking for a high-level way to do this. Of course, the more details you can provide the better 🙂
This is not a caching problem but a data de-normalization problem. If you have a record with the correct value in it, reading that value out is trivial and will take no time even if done hundreds of times per second. You can benchmark it to be sure.
It’s usually easy to do this with an
after_createhook where you twiddle some value:If you need to cache because database performance isn’t satisfactory, use the
Rails.cachefacility with Memcache as a store so this data is shared between instances of Rails. Each time you record a sale, add the appropriate amount to the cached value. If the cache isn’t populated, pull the sum from the database.