Skip to content

Instantly share code, notes, and snippets.

@tpasipanodya
Created August 30, 2019 01:41
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 tpasipanodya/e7cbe9d3cd8903022dad3e2d197ed612 to your computer and use it in GitHub Desktop.
Save tpasipanodya/e7cbe9d3cd8903022dad3e2d197ed612 to your computer and use it in GitHub Desktop.
The Lua Script to Reserve a Job
redis.replicate_commands()
local queue = ARGV[1]
-- randomly select a tenant
local runnable_tenants = queue .. '_runnable_tenants'
local tenant_id = redis.call('SRANDMEMBER', runnable_tenants)
-- get their next pending job
local pending_jobs = queue .. '_pending_jobs:' .. tenant_id
local job_id = redis.call('RPOP', pending_jobs)
-- update all other structures to be in the running state
local running_jobs = queue .. '_running_jobs:' .. tenant_id
redis.call('SADD', running_jobs, job_id)
-- If reserving this job brings a tenant above the limit, they become un-runnable
local runing_jobs_count = redis.call('SCARD', running_jobs)
local limit = tonumber(redis.call('HGET', 'tenant_limits', queue))
if (runing_jobs_count >= limit) then
local runnable_tenants = queue .. '_runnable_tenants'
redis.call('SREM', runnable_tenants, tenant_id)
end
return {job_id, tenant_id}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment