Skip to content

Instantly share code, notes, and snippets.

@mironovdm
Created June 10, 2024 23:51
Show Gist options
  • Select an option

  • Save mironovdm/27e9311d42577b26523cb83d20ba8170 to your computer and use it in GitHub Desktop.

Select an option

Save mironovdm/27e9311d42577b26523cb83d20ba8170 to your computer and use it in GitHub Desktop.
Redis work in progress counter with items timeout

Timeout may be necessary if the delition of an item cannot be garanted.

Call example:

EVAL f572d396fae9206628714fb2ce00f72e94f2258f 2 wip_key evict_key itemVal <now + timeout> wip_limit evictPeriodSec now
local function get_wip_count(wip_items_key, eviction_check_key, eviction_period, current_timestamp)
local wip_count = tonumber(redis.call("ZCARD", wip_items_key)) or 0
if wip_count == 0 then
return 0
end
local evict_now = redis.call("GET", eviction_check_key) == false
if evict_now then
local removed = tonumber(redis.call("ZREMRANGEBYSCORE", wip_items_key, "-inf", "("..current_timestamp))
wip_count = wip_count - removed
redis.call("SETEX", eviction_check_key, eviction_period, "1")
end
return wip_count
end
local wip_items_key = KEYS[1]
local eviction_check_key = KEYS[2]
local value = ARGV[1]
local remove_after_timestamp = ARGV[2]
local total_limit = tonumber(ARGV[3])
local eviction_period = tonumber(ARGV[4])
local current_timestamp = tonumber(ARGV[5])
local wip_count = get_wip_count(wip_items_key, eviction_check_key, eviction_period, current_timestamp)
if wip_count < total_limit then
redis.call("ZADD", wip_items_key, remove_after_timestamp, value)
return {1, wip_count}
end
return {0, wip_count}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment