Skip to content

Instantly share code, notes, and snippets.

@tpasipanodya
Created Aug 30, 2019
Embed
What would you like to do?
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