Skip to content
A replacement for Rails' counter caches, using memcached
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.
lib Revert "Merge pull request #5 from academia-edu/async-calculation-sup… Jul 19, 2019
spec Ensure after_commit hook exceptions are propagated in tests May 8, 2016
.gitignore Switch from RDoc to YARD May 10, 2016
.travis.yml Initial commit (ported from app) May 8, 2016
Gemfile Remove non-working AR master config from Gemfile May 8, 2016
README.rdoc README: Add build status Feb 11, 2017
incrdecr_cached_counts.gemspec Remove support for Rails 4.0 and 4.1 Sep 24, 2017



A replacement for Rails' counter caches, using memcached.

Caches counts of models in a scope or association in memcached, and keeps the cache up to date using incr/decr operations.

You might prefer this gem over Rails' built-in counter caches when:

  • You want to cache the total number of models for a class or scope

  • You have a large association (e.g. followers of a popular figure) and want to avoid contention on a database row

  • You want your caches to occasionally expire and be refreshed to mitigate the risk of getting out of sync

  • You don't need to use counts as part of more complex SQL queries

There are many alternatives, but this gem appears to be unique in its approach. Other gems solve the contention issue by pushing updates to a background job, which has the advantage of continuing to populate a column that can be queried via SQL, but is still more costly than our approach, while introducing a synchronization delay.



Basic usage:

class User < ActiveRecord::Base
  include CachedCounts

  has_many :followers, class_name: 'Following' #, ...
  scope :confirmed, ->{ where(confirmed: true) }

  # creates cached class method `User.confirmed_count`
  caches_count_where :confirmed, if: :confirmed?

  # creates cached instance method `user.followers_count`
  caches_count_of :followers

class Following < ActiveRecord::Base
  include CachedCounts

  belongs_to :followee, class_name: 'User' #, ...

Note that CachedCounts must be included in the counted class, but no class methods need be called there.

For full options, see docs for CachedCounts.caches_count_of and CachedCounts.caches_count_where.





Bug reports and pull requests are welcome on GitHub at

You can’t perform that action at this time.