Skip to content

Instantly share code, notes, and snippets.

@senderista
Last active August 26, 2015 23:13
Show Gist options
  • Save senderista/ebdd24dd649fafd083c0 to your computer and use it in GitHub Desktop.
Save senderista/ebdd24dd649fafd083c0 to your computer and use it in GitHub Desktop.
OpenResty rate limiter example
worker_processes 1;
error_log logs/error.log;
events {
worker_connections 1024;
}
http {
lua_shared_dict token_bucket 10m;
init_by_lua '
ngx.shared.token_bucket:set("tokens_avail", 0)
ngx.shared.token_bucket:set("last_timestamp", os.time())
';
server {
listen 8098;
location / {
default_type text/html;
access_by_lua '
local TOKEN_ACCUM_RATE = 0.1
local BUCKET_SIZE = 5
local TOKENS_PER_REQ = 1
local last_timestamp = ngx.shared.token_bucket:get("last_timestamp")
local cur_timestamp = os.time()
local time_elapsed = cur_timestamp - last_timestamp
local tokens_accum = time_elapsed * TOKEN_ACCUM_RATE
local tokens_avail = ngx.shared.token_bucket:get("tokens_avail")
tokens_avail = math.min(tokens_avail + tokens_accum, BUCKET_SIZE)
if tokens_avail >= TOKENS_PER_REQ then
ngx.shared.token_bucket:set("tokens_avail", tokens_avail - TOKENS_PER_REQ)
ngx.shared.token_bucket:set("last_timestamp", cur_timestamp)
ngx.exit(ngx.OK)
else
-- we have to set the status here because we call ngx.say(),
-- forcing response headers to be sent immediately
-- https://github.com/openresty/lua-resty-redis/issues/15#issuecomment-14747652
ngx.status = 429
ngx.say(tokens_avail)
ngx.say("Request failed")
ngx.exit(429)
end
';
content_by_lua '
ngx.say(ngx.shared.token_bucket:get("tokens_avail"))
ngx.say("Request successful")
';
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment