Ask, Discuss and Reason...

#vaadit

ask
discuss
reason

#vaadit

How I improved Rails performance by 10x in 15 minutes using Redis caching.

08 Aug 2019 8:39 AM
by: Sachin Mudgal | category: rails

Requisite: Rails, Redis, gem redis, gem redis-namespace

Redis or simply RAM storage. You most probably already be using Redis with your Background Jobs processing in Rails.

Now lets use it for caching with simple 15 minutes if implementation at max.

  • In your Gemfile: gem 'redis-namespace' (Source: https://github.com/resque/redis-namespace)
  • In your Gemfile: gem 'redis' (Source: https://github.com/redis/redis-rb)
  • class User < ApplicationRecord # Callbacks after_save :delete_redis_cache def self.redis_key_for(id) "user-id-#{id}" end # Override 'find_by_id' method def self.find_by_id(id) redis_connection = Redis.new namespaced_redis = Redis::Namespace.new(:modelcache, redis: redis_connection) user_from_redis = namespaced_redis.get(redis_key_for(id)) if user_from_redis.blank? user = super(id) if user.present? namespaced_redis.set(redis_key_for(id), user.attributes.to_json) else return nil end else user = User.new(JSON.parse(user_from_redis)) end return user end # Clear redis user cache def delete_redis_cache redis_connection = Redis.new namespaced_redis = Redis::Namespace.new(:modelcache, redis: redis_connection) namespaced_redis.del(User.redis_key_for(id)) end end
  • redis_key_for does keeps same key. Key is important as it's the unique identifier
  • find_by_id overrides rails method and first tries to find it in Redis, and if it's not found then fetch from DB and sets redis
  • Best way to save into Redis is JSON form as it's just a string based db store. So we just to to_json before storing into Redis and then doing User.new(JSON.parse(user_from_redis)) after getting it from Redis.
  • After every save we are clearing its redis cache with delete_redis_cache. You can improve it to clear and reset or clear selectively.

That's it.

PS: I didn't go much into Redis config, but this article is anyway written thinking you have already setup Redis. Otherwise just go to the aforementioned gems documentations.

Please excuse for any obvious errors.