Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I'd be curious to see the Lua code that implements this. Anyone care to indulge me?


I'm guessing it would look something like this... I omitted checking if the token is in the 1 minute window. It returns false if the user has reached the rate limit, true if the user has more tokens left. If the user has tokens left, it decrements the token the user has left before returning true.

  local id = "user_1"
  -- Get the number of tokens the user has left
  local tokens = redis.call("HGET", id, "tokens")
  if tokens = 0 then
    -- User has no tokens left
    return false
  else
    -- User has tokens left, decrement token count
    redis.call("HINCRBY", id, "tokens" -1)
    return true
  end
Redis lua scripts block while they are running, so the two redis calls here cannot be interleaved with other reads, as in the token bucket example from the article.


thats really not bad at all.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: