rack-throttle icon indicating copy to clipboard operation
rack-throttle copied to clipboard

Add cache expiration for Redis

Open GuyPaddock opened this issue 8 years ago • 5 comments

It seems like the per-second / per-minute / etc. keys that rack-throttle creates in Redis are permanent. We run a high traffic site, which means that we're going to end up with a lot of pollution and wasted space in Redis. Ideally, there should be some way for these keys to expire.

GuyPaddock avatar Oct 05 '16 02:10 GuyPaddock

Just reduced the scope. Memcached isn't much of an issue, but Redis is not always configured to be a cache, so it'd be great if rack-throttle could set an appropriate expiration.

GuyPaddock avatar Oct 05 '16 03:10 GuyPaddock

Hmm, one suggestion I would have to do this is to implement your own rack-throttle cache store. The cache is meant to be very flexible you can try something like this:

class ThrottleCache
  def set(key, value)
    redis_client.set(key, value)
    redis_client.expire(key, your_expire_time)
  end

  def get(key)
    redis_client.get(key)
  end
end

rack-throttle is really cache agnostic, and doesn't really do much with the cache besides try to set keys, and retrieve them.

FreekingDean avatar Oct 05 '16 03:10 FreekingDean

That example assumes redis_client is setup to your liking in the class in some private function/variable/etc.

You can then setup rack-throttle via:

use Rack::Throttle::Interval, :cache => ThrottleCache.new
#or
config.middleware.use Rack::Throttle::Interval, :cache => ThrottleCache.new

FreekingDean avatar Oct 05 '16 03:10 FreekingDean

I'd considered that, but didn't realize it would be quite that straightforward. I was just working on a PR that would allow RT to detect if the cache supports expiration, so that each provider could provide a recommended expiration, but I think the approach you're recommending is much cleaner.

GuyPaddock avatar Oct 05 '16 03:10 GuyPaddock

Yup! I think until we decide on a "Best Practices" or start implementing true cache specific code it might be best to leave the expiry up to the user. That all being said! I think that it might be good to include this as an example :). I'm going to start working on 'wiki-ifying' the instructions one of these days.

FreekingDean avatar Oct 05 '16 03:10 FreekingDean