Interview frequency: …
Short answer
Use SET with NX and PX options to store a random token with a timeout, and release the lock with a Lua script that verifies the token.
Explanation
When several Node.js server instances run a critical operation (such as debiting a balance or reserving a single seat), in-memory variables are not enough. Acquire the lock atomically through Redis: SET lock_key my_unique_token NX PX 30000. Release it only through a Lua Script so you do not delete a lock that expired and was acquired by another server.
Code example
// Lua script To release the atomic lock
const releaseScript = `
if redis.call("get", KEYS[1]) == ARGV[1] then
return redis.call("del", KEYS[1])
else
return 0
end
`;Common mistakes
- Releasing the lock with a simple DEL command without checking whether the token still belongs to the current operation.