ActiveRecordCached
This gem adds methods to cache small amounts of ActiveRecord data in RAM, Redis, or other stores.
The cache for each model is busted both by individual CRUD operations on that model (e.g. #update
), as well as by mass operations (e.g. #update_all
).
The cached methods work on whole models as well as on relations.
There is an automatic warning if the data is getting too big to cache.
Installation
Install the gem and add to the application's Gemfile by executing:
$ bundle add activerecord_cached
Usage
Pizza.cached_count
Pizza.limit(2).cached_pluck(:name)
Pizza.select(:id, :name).cached_records
Configuration:
ActiveRecordCached.configure do |config|
config.cache_store = Rails.cache
config.max_total_bytes = 16.megabytes
config.max_bytes = 2.megabytes
config.max_count = 1000
config.on_limit_reached = ->msg{ report(msg) }
end
Specs:
RSpec.configure do |config|
config.after(:each) { ActiveRecordCached.clear_all }
end
Tradeoffs
The default MemoryStore is orders of magnitude faster than e.g. Redis, but it is wiped when the app is deployed or otherwise restarted, which may present a cache stampede risk under very high load.
Contributing
Bug reports and pull requests are welcome on GitHub at https://github.com/jaynetics/activerecord_cached.
License
The gem is available as open source under the terms of the MIT License.