Video in progress

Strong Middle ⚡ Redis and caching

At most 5 heavy export jobs should run at once, and the application runs on 10 pods. How do you build a distributed semaphore in Redis?

A plain INCR/DECR counter "eats" a permit when a pod dies. A better way is a Sorted Set: the member is the permit token, the score is its expiry time. In Lua you clear out the expired ones and ZADD if ZCARD is below the limit, keep updating the score during the work, and ZREM at the end.

📖 Answer

The naive version:

if (redis.opsForValue().increment("export:slots") > 5) {
    redis.opsForValue().decrement("export:slots");
    throw new BusyException();
}
try { runExport(); } finally { redis.opsForValue().decrement("export:slots"); }

If a pod dies from an OOM, the finally never runs. A week later the counter is stuck at 5 and no export can run.

With expiring permits:

-- KEYS[1]=semaphore, ARGV[1]=limit, ARGV[2]=lease ms, ARGV[3]=token
local t = redis.call('TIME')
local now = tonumber(t[1]) * 1000 + math.floor(tonumber(t[2]) / 1000)
redis.call('ZREMRANGEBYSCORE', KEYS[1], '-inf', now)
if redis.call('ZCARD', KEYS[1]) < tonumber(ARGV[1]) then
  redis.call('ZADD', KEYS[1], now + tonumber(ARGV[2]), ARGV[3])
  return 1
end
return 0
  • the time comes from Redis's TIME command, so the result is correct even if the pods' clocks differ;
  • during the work, every 10 seconds, ZADD semaphore XX <new expiry> <token> as a heartbeat;
  • when it's done, ZREM semaphore <token>;
  • if a pod dies, the heartbeat stops and the permit frees itself when the lease ends.

There's a ready-made option too: Redisson's RPermitExpirableSemaphore.

The same limitation as with a lock applies here: during a long GC pause, the permit can expire and a 6th export can start. For exports this is usually harmless, since here the semaphore protects a resource, not correctness.