Skip to content

Instantly share code, notes, and snippets.

@NaN1488
Created December 6, 2018 14:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NaN1488/7a142b7ee3b90bd2eba3e64c195a2a68 to your computer and use it in GitHub Desktop.
Save NaN1488/7a142b7ee3b90bd2eba3e64c195a2a68 to your computer and use it in GitHub Desktop.
Rate Limiter with redis
def can_call?(name, seconds, limit)
calls = redis.llen(name)
return false if calls > limit
if redis.exists(name)
redis.rpushx(name, 1)
else
redis.multi do
redis.rpush(name, 1)
redis.expire(name, seconds)
end
end
true
end
#in worker
secs = 60*60
name = 'api_name'
limit = 5000 # calls per hour (secs)
if can_call?(name, secs, limit)
exec_call
else
re-enqueue
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment